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): adapt to PromptAttachmentManager and migrate dynamic prompt context out of system prompt

MengHan1821fa3c85bd87
diff --git a/jiuwenswarm/agents/harness/common/rails/avatar_rail.py b/jiuwenswarm/agents/harness/common/rails/avatar_rail.py
index 974f40a788..2522314c91 100644
--- a/jiuwenswarm/agents/harness/common/rails/avatar_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/avatar_rail.py
@@ -3,35 +3,43 @@
"""AvatarPromptRail - 数字分身 Rail.
处理所有 per-request 的 avatar 逻辑:
-1. before_model_call: 根据 ContextVar 动态注入/移除 avatar 相关 PromptSection
+1. before_model_call: 根据 ContextVar 动态写入/清理 TURN prompt attachment
2. before_tool_call: 拦截群聊记忆禁写 + enable_memory=False 场景
"""
from __future__ import annotations
-from typing import Any, Optional, Set
-
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,
+ PromptAttachmentScope,
+)
from openjiuwen.harness.rails.base import DeepAgentRail
from jiuwenswarm.agents.harness.common.rails.permissions.owner_scopes import (
TOOL_PERMISSION_CONTEXT,
- PermissionContext,
)
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 动态注入/移除 avatar 相关 PromptSection
+ 1. before_model_call: 根据 ContextVar 动态写入/清理 TURN prompt attachment
2. before_tool_call: 拦截群聊记忆禁写 + enable_memory=False 场景
"""
@@ -39,7 +47,14 @@ class AvatarPromptRail(DeepAgentRail):
def __init__(self) -> None:
super().__init__()
- self._injected_sections: set[str] = set()
+ 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
async def before_model_call(self, ctx: AgentCallbackContext) -> None:
builder = getattr(
@@ -47,44 +62,35 @@ class AvatarPromptRail(DeepAgentRail):
"system_prompt_builder",
None,
)
- 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"
+ language = getattr(builder, "language", "cn") if builder is not None else "cn"
+ language = language or "cn"
+ sections: list[PromptSection] = []
try:
from jiuwenswarm.agents.harness.common.memory.forbidden import get_forbidden_memory_prompt
forbidden = get_forbidden_memory_prompt(language)
if forbidden:
- section = PromptSection(
+ sections.append(PromptSection(
name="forbidden_memory",
content={language: forbidden},
- priority=_AVATAR_PROMPT_PRIORITY + 3,
- )
- builder.add_section(section)
- self._injected_sections.add("forbidden_memory")
+ priority=_AVATAR_SECTION_PRIORITIES["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
- avatar_content = _build_avatar_prompt(display_name, language)
- section = PromptSection(
+ sections.append(PromptSection(
name="avatar_identity",
- content={language: avatar_content},
- priority=_AVATAR_PROMPT_PRIORITY,
- )
- builder.add_section(section)
- self._injected_sections.add("avatar_identity")
+ content={language: _build_avatar_prompt(display_name, language)},
+ priority=_AVATAR_SECTION_PRIORITIES["avatar_identity"],
+ ))
# 判断是否为群聊数字分身模式(三个条件同时满足)
is_group_digital_avatar = (
@@ -99,13 +105,11 @@ class AvatarPromptRail(DeepAgentRail):
if language == "cn"
else "\n[Group chat mode: write_memory/edit_memory calls are prohibited]\n"
)
- section = PromptSection(
+ sections.append(PromptSection(
name="group_chat_memory_notice",
content={language: notice},
- priority=_AVATAR_PROMPT_PRIORITY + 1,
- )
- builder.add_section(section)
- self._injected_sections.add("group_chat_memory_notice")
+ priority=_AVATAR_SECTION_PRIORITIES["group_chat_memory_notice"],
+ ))
# 记忆完全禁用(三个条件同时满足:enable_memory=False + group_digital_avatar=True + 群聊消息)
should_disable_memory = (
@@ -114,24 +118,20 @@ class AvatarPromptRail(DeepAgentRail):
and perm_ctx.avatar_mode
)
if should_disable_memory:
- disabled_content = _build_memory_fully_disabled_prompt(language)
- section = PromptSection(
+ sections.append(PromptSection(
name="memory_fully_disabled",
- content={language: disabled_content},
- priority=_AVATAR_PROMPT_PRIORITY + 2,
- )
- builder.add_section(section)
- self._injected_sections.add("memory_fully_disabled")
+ content={language: _build_memory_fully_disabled_prompt(language)},
+ priority=_AVATAR_SECTION_PRIORITIES["memory_fully_disabled"],
+ ))
if is_group_digital_avatar:
- interaction_content = _build_interaction_prompt(language)
- section = PromptSection(
+ sections.append(PromptSection(
name="interaction_guidance",
- content={language: interaction_content},
- priority=_AVATAR_PROMPT_PRIORITY + 4,
- )
- builder.add_section(section)
- self._injected_sections.add("interaction_guidance")
+ content={language: _build_interaction_prompt(language)},
+ priority=_AVATAR_SECTION_PRIORITIES["interaction_guidance"],
+ ))
+
+ await self._sync_avatar_sections(ctx, sections, language=language)
async def before_tool_call(self, ctx: AgentCallbackContext) -> None:
"""拦截记忆工具调用。
@@ -184,6 +184,37 @@ 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.for_context(ctx)
+ for section in _AVATAR_SECTION_PRIORITIES:
+ await writer.clear_section(
+ section=section,
+ scope=PromptAttachmentScope.TURN,
+ )
+ for section in sections:
+ await writer.upsert_from_section(
+ section=section,
+ scope=PromptAttachmentScope.TURN,
+ 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 ab5d17abb3..68375f7950 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 ``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.
+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.
This rail lives in jiuwenswarm (not agent-core) so that:
@@ -18,6 +18,10 @@ 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,
+ PromptAttachmentScope,
+)
from openjiuwen.harness.rails.base import DeepAgentRail
from jiuwenswarm.agents.harness.common.rails.project_memory import (
@@ -34,7 +38,7 @@ if TYPE_CHECKING:
class ProjectMemoryRail(DeepAgentRail):
- """Auto-load project memory files and inject them into the system prompt.
+ """Auto-load project memory files and inject them as a prompt attachment.
Loaded sources (all read-only; only ``JIUWENSWARM.md`` and
``JIUWENSWARM.local.md`` are written by ``/init``):
@@ -80,17 +84,19 @@ class ProjectMemoryRail(DeepAgentRail):
self._language: str = language
self._max_chars: int = max_chars
self._additional_directories: tuple[str, ...] = tuple(additional_directories or ())
- self._system_prompt_builder = None
+ self._agent = None
+ self.attachment_manager = None
# ------------------------------------------------------------------
# Lifecycle
# ------------------------------------------------------------------
def init(self, agent: "DeepAgent") -> None:
- self._system_prompt_builder = getattr(agent, "system_prompt_builder", None)
- if self._system_prompt_builder is None:
+ self._agent = agent
+ self.attachment_manager = getattr(agent, "prompt_attachment_manager", None)
+ if self.attachment_manager is None:
logger.warning(
- "[ProjectMemoryRail] agent has no system_prompt_builder; disabled"
+ "[ProjectMemoryRail] agent has no prompt attachment manager; disabled"
)
return
logger.info(
@@ -100,15 +106,11 @@ class ProjectMemoryRail(DeepAgentRail):
)
def uninit(self, agent: "DeepAgent") -> None:
- """Clear the injected section to avoid stale content on rail swap."""
+ """Clear discovery cache on rail swap."""
+ del agent
clear_project_memory_cache(self.resolve_workspace_path())
- if self._system_prompt_builder is not None:
- try:
- self._system_prompt_builder.remove_section(SECTION_NAME)
- except Exception as exc: # noqa: BLE001 -- defensive; never crash teardown
- logger.warning(
- "[ProjectMemoryRail] remove_section on uninit failed: %s", exc
- )
+ self._agent = None
+ self.attachment_manager = None
# ------------------------------------------------------------------
# Public knobs (per-request hot updates, parallel to RuntimePromptRail)
@@ -146,8 +148,8 @@ class ProjectMemoryRail(DeepAgentRail):
# ------------------------------------------------------------------
async def before_model_call(self, ctx: AgentCallbackContext) -> None: # noqa: ARG002
- """Refresh the ``project_memory`` section from cached discovery state."""
- if self._system_prompt_builder is None:
+ """Refresh the session-scoped ``project_memory`` attachment."""
+ if self._agent is None:
return
workspace_path = self.resolve_workspace_path()
@@ -172,15 +174,8 @@ 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.
- try:
- self._system_prompt_builder.remove_section(SECTION_NAME)
- except Exception as exc: # noqa: BLE001 -- builder API surface is broad
- logger.warning(
- "[ProjectMemoryRail] remove_section failed (continuing): %s", exc
- )
-
if not merged.strip():
+ await self._clear_prompt_attachment(ctx)
return
section = build_project_memory_section(
@@ -189,7 +184,7 @@ class ProjectMemoryRail(DeepAgentRail):
priority=self.SECTION_PRIORITY,
)
if section is not None:
- self._system_prompt_builder.add_section(section)
+ await self._upsert_prompt_attachment(ctx, section)
async def after_tool_call(self, ctx: AgentCallbackContext) -> None:
"""Explicitly invalidate memory discovery cache after write-like tools."""
@@ -217,5 +212,34 @@ 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.for_context(ctx).upsert_from_section(
+ section=section,
+ scope=PromptAttachmentScope.SESSION,
+ 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.for_context(ctx).clear_section(
+ section=SECTION_NAME,
+ scope=PromptAttachmentScope.SESSION,
+ )
+ 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 07f4b63b66..ad28f19141 100644
--- a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py
@@ -16,6 +16,10 @@ import yaml
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
from openjiuwen.harness.prompts import PromptSection
+from openjiuwen.harness.prompts.prompt_attachment_manager import (
+ PromptAttachmentKind,
+ PromptAttachmentScope,
+)
from openjiuwen.harness.rails.base import DeepAgentRail
from jiuwenswarm.agents.harness.common.prompt.shell_environment import build_shell_environment_prompt
from jiuwenswarm.common.utils import get_config_dir, logger
@@ -38,6 +42,7 @@ class RuntimePromptRail(DeepAgentRail):
) -> None:
super().__init__()
self.system_prompt_builder = None
+ self.attachment_manager = None
self._language = language
self._channel = channel
self._trusted_dirs: list[str] | None = None
@@ -50,6 +55,7 @@ class RuntimePromptRail(DeepAgentRail):
def init(self, agent) -> None:
"""从 agent 获取 system_prompt_builder 引用。"""
self.system_prompt_builder = getattr(agent, "system_prompt_builder", None)
+ self.attachment_manager = getattr(agent, "prompt_attachment_manager", None)
def uninit(self, agent) -> None:
"""清理注入的 section 并释放引用。"""
@@ -62,6 +68,7 @@ class RuntimePromptRail(DeepAgentRail):
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
def set_language(self, language: str) -> None:
"""per-request 更新语言。"""
@@ -127,6 +134,9 @@ class RuntimePromptRail(DeepAgentRail):
if not self.system_prompt_builder:
return
+ for name in ("runtime", "language_output", "env", "git_status", "trusted_dirs_policy"):
+ self.system_prompt_builder.remove_section(name)
+
if not self._force_english and self._language == "cn":
time_content = (
f"# 时间说明\n\n"
@@ -186,14 +196,17 @@ class RuntimePromptRail(DeepAgentRail):
"do NOT introduce yourself or list capabilities."
)
- self.system_prompt_builder.add_section(PromptSection(
- name="runtime",
- content={"cn": runtime_content, "en": runtime_content},
+ await self._upsert_prompt_attachment(
+ ctx,
+ section="runtime",
+ content=runtime_content,
+ scope=PromptAttachmentScope.TURN,
+ kind=PromptAttachmentKind.RUNTIME,
+ source="jiuwenswarm.runtime_prompt.runtime",
priority=95,
- ))
+ )
# ── Language output constraint (injected near end, like Claude Code) ──
- self.system_prompt_builder.remove_section("language_output")
language_name = _LANGUAGE_NAMES.get(language_val, language_val)
language_output_content = (
"# Language\n\n"
@@ -203,11 +216,15 @@ class RuntimePromptRail(DeepAgentRail):
f"Technical terms and code identifiers should remain "
f"in their original form."
)
- self.system_prompt_builder.add_section(PromptSection(
- name="language_output",
- content={"cn": language_output_content, "en": language_output_content},
+ await self._upsert_prompt_attachment(
+ ctx,
+ section="language_output",
+ content=language_output_content,
+ scope=PromptAttachmentScope.TURN,
+ kind=PromptAttachmentKind.RUNTIME,
+ source="jiuwenswarm.runtime_prompt.language_output",
priority=93,
- ))
+ )
# ── Platform / OS environment section ──
os_type = sys.platform
@@ -281,7 +298,6 @@ class RuntimePromptRail(DeepAgentRail):
))
# ── Git status section ──
- self.system_prompt_builder.remove_section("git_status")
git_branch = str(runtime_state.get("git_branch") or "").strip()
if git_branch and git_branch != "N/A":
git_main_branch = str(runtime_state.get("git_main_branch") or "").strip()
@@ -305,11 +321,21 @@ class RuntimePromptRail(DeepAgentRail):
git_content = "\n\n".join(git_lines)
- self.system_prompt_builder.add_section(PromptSection(
- name="git_status",
- content={"cn": git_content, "en": git_content},
+ await self._upsert_prompt_attachment(
+ ctx,
+ section="git_status",
+ content=git_content,
+ scope=PromptAttachmentScope.SESSION,
+ kind=PromptAttachmentKind.WORKSPACE_DELTA,
+ source="jiuwenswarm.runtime_prompt.git_status",
priority=87,
- ))
+ )
+ else:
+ await self._clear_prompt_attachment(
+ ctx,
+ section="git_status",
+ scope=PromptAttachmentScope.SESSION,
+ )
self.system_prompt_builder.remove_section("browser_tool_policy")
if self._channel == "web":
@@ -324,13 +350,22 @@ 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."
)
- self.system_prompt_builder.add_section(PromptSection(
- name="browser_tool_policy",
- content={"cn": browser_tool_policy, "en": browser_tool_policy},
+ await self._upsert_prompt_attachment(
+ ctx,
+ section="browser_tool_policy",
+ content=browser_tool_policy,
+ scope=PromptAttachmentScope.TURN,
+ kind=PromptAttachmentKind.RUNTIME,
+ source="jiuwenswarm.runtime_prompt.browser_tool_policy",
priority=98,
- ))
+ )
+ else:
+ await self._clear_prompt_attachment(
+ ctx,
+ section="browser_tool_policy",
+ scope=PromptAttachmentScope.TURN,
+ )
- self.system_prompt_builder.remove_section("trusted_dirs_policy")
if self._channel == "tui":
# Trusted directories policy for TUI mode
trusted_dirs = self._existing_dirs(self._trusted_dirs)
@@ -388,10 +423,62 @@ class RuntimePromptRail(DeepAgentRail):
"- When confirming, clearly state: the full path, operation type (read/edit/execute), "
"potential risks\n"
)
- self.system_prompt_builder.add_section(PromptSection(
- name="trusted_dirs_policy",
- content={"cn": trusted_dirs_content, "en": trusted_dirs_content},
+ await self._upsert_prompt_attachment(
+ ctx,
+ section="trusted_dirs",
+ content=trusted_dirs_content,
+ scope=PromptAttachmentScope.TURN,
+ kind=PromptAttachmentKind.WORKSPACE_DELTA,
+ source="jiuwenswarm.runtime_prompt.trusted_dirs",
priority=90,
- ))
+ )
else:
self.system_prompt_builder.remove_section("trusted_dirs_policy")
+
+ async def _upsert_prompt_attachment(
+ self,
+ ctx: AgentCallbackContext,
+ *,
+ section: str,
+ content: str,
+ scope: PromptAttachmentScope,
+ kind: PromptAttachmentKind,
+ source: str,
+ priority: int,
+ ) -> None:
+ if self.attachment_manager is None:
+ logger.warning(
+ "[RuntimePromptRail] prompt attachment manager unavailable; skip dynamic section=%s",
+ section,
+ )
+ return
+ try:
+ writer = self.attachment_manager.for_context(ctx)
+ await writer.upsert_section(
+ section=section,
+ content=content,
+ scope=scope,
+ kind=kind,
+ source=source,
+ priority=priority,
+ content_kind="text/markdown",
+ )
+ except ValueError as exc:
+ logger.warning("[RuntimePromptRail] skip prompt attachment section=%s: %s", section, exc)
+
+ async def _clear_prompt_attachment(
+ self,
+ ctx: AgentCallbackContext,
+ *,
+ section: str,
+ scope: PromptAttachmentScope,
+ ) -> None:
+ if self.attachment_manager is None:
+ return
+ try:
+ await self.attachment_manager.for_context(ctx).clear_section(
+ section=section,
+ scope=scope,
+ )
+ except ValueError as exc:
+ logger.warning("[RuntimePromptRail] skip clearing prompt attachment section=%s: %s", section, exc)
diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.py
index 38aea260cc..b937484b88 100644
--- a/jiuwenswarm/common/utils.py
+++ b/jiuwenswarm/common/utils.py
@@ -1294,6 +1294,12 @@ def get_agent_workspace_dir() -> Path:
return get_agent_root_dir() / "workspace"
+def get_prompt_attachment_dir() -> Path:
+ """Get the jiuwenswarm prompt attachment directory path."""
+
+ return get_agent_workspace_dir() / "prompt_attachment"
+
+
def get_agent_root_dir() -> Path:
return get_user_workspace_dir() / "agent"
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 72a9174c86..fb1417340b 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -51,6 +51,7 @@ from openjiuwen.harness import (
)
from openjiuwen.harness.factory import create_deep_agent
from openjiuwen.harness.prompts import resolve_language
+from openjiuwen.harness.prompts.prompt_attachment_manager import PromptAttachmentScope
from openjiuwen.harness.rails import (
SkillUseRail,
TaskPlanningRail,
@@ -144,6 +145,7 @@ from jiuwenswarm.server.runtime.session.session_metadata import build_server_pus
from jiuwenswarm.server.runtime.session.session_history import append_history_record
from jiuwenswarm.server.runtime.skill import filter_visible_skill_names
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
+from jiuwenswarm.server.runtime.prompt_attachment_loader import PromptAttachmentLoader
from jiuwenswarm.server.runtime.agent_adapter.evolution_helpers import (
EVOLUTION_ACCEPT_LABELS,
EVOLUTION_EXECUTE_LABELS,
@@ -240,6 +242,7 @@ from jiuwenswarm.common.utils import (
get_deepagent_soul_md_path,
get_deepagent_user_md_path,
get_env_file,
+ get_prompt_attachment_dir,
reset_free_search_runtime_flags,
)
@@ -549,6 +552,7 @@ class JiuWenClawDeepAdapter:
self._context_processor_rail: ContextProcessorRail | None = None
self._runtime_prompt_rail: RuntimePromptRail | None = None
self._response_prompt_rail: ResponsePromptRail | None = None
+ self._prompt_attachment_loader: PromptAttachmentLoader | None = None
self._security_rail: SecurityRail | None = None
self._memory_rail: MemoryRail | None = None
self._external_memory_rail: Any = None
@@ -886,7 +890,7 @@ class JiuWenClawDeepAdapter:
self._a2x_config.get("role", "teammate"),
self._a2x_config.get("base_url", ""),
)
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
self._a2x_client = None
self._a2x_config = {}
self._a2x_blank_service_id = ""
@@ -2091,7 +2095,7 @@ class JiuWenClawDeepAdapter:
from openjiuwen.extensions.sys_operation.sandbox.providers.jiuwenbox import (
force_recreate_jiuwenbox_sandbox,
)
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
logger.warning(
"[JiuWenSwarmDeepAdapter] force_recreate_jiuwenbox_sandbox import "
"failed: %s",
@@ -2110,7 +2114,7 @@ class JiuWenClawDeepAdapter:
"[JiuWenSwarmDeepAdapter] sandbox instance recreated: %s",
new_sandbox_id,
)
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
logger.warning(
"[JiuWenSwarmDeepAdapter] force_recreate_jiuwenbox_sandbox "
"failed: %s",
@@ -2871,6 +2875,8 @@ class JiuWenClawDeepAdapter:
"project_dir", config.get("project_dir")
)
self._workspace_dir = config.get("workspace_dir", str(get_agent_workspace_dir()))
+ self._prompt_attachment_loader = PromptAttachmentLoader(self._prompt_attachment_root())
+ self._prompt_attachment_loader.ensure_layout()
model = self._create_model(config_base)
await self._try_init_a2x_client(config_base)
@@ -2940,6 +2946,49 @@ class JiuWenClawDeepAdapter:
# 动态加载用户自定义的 Rail 扩展
await self.load_user_rails()
+ async def _sync_prompt_attachments_for_request(self, session_id: str, invoke_turn_id: str) -> None:
+ """Hot-load prompt attachment files for the current request.
+
+ Prompt attachment loading must not block the user request path. Failures are
+ logged and the original Runner flow continues without attachment injection.
+ """
+
+ if self._instance is None:
+ return
+ if self._prompt_attachment_loader is None:
+ self._prompt_attachment_loader = PromptAttachmentLoader(self._prompt_attachment_root())
+ self._prompt_attachment_loader.ensure_layout()
+ try:
+ await self._prompt_attachment_loader.sync_to_agent(
+ self._instance,
+ session_id=session_id,
+ invoke_turn_id=invoke_turn_id,
+ )
+ except Exception as exc:
+ logger.warning("[JiuWenClawDeepAdapter] prompt attachment sync skipped: %s", exc)
+
+ async def _clear_prompt_attachments_for_request(self, session_id: str, invoke_turn_id: str) -> None:
+ """Clear all turn-scope prompt attachments for one completed request."""
+
+ if self._instance is None:
+ return
+ manager = getattr(self._instance, "prompt_attachment_manager", None)
+ if manager is None:
+ return
+ try:
+ await manager.remove_by_filter(
+ session_id=session_id,
+ invoke_turn_id=invoke_turn_id,
+ scope=PromptAttachmentScope.TURN,
+ )
+ except Exception as exc:
+ logger.warning("[JiuWenClawDeepAdapter] prompt attachment turn cleanup skipped: %s", exc)
+
+ def _prompt_attachment_root(self) -> Path:
+ if self._workspace_dir == str(get_agent_workspace_dir()):
+ return get_prompt_attachment_dir()
+ return Path(self._workspace_dir) / "prompt_attachment"
+
async def load_user_rails(self) -> None:
"""动态加载用户自定义的 Rail 扩展."""
try:
@@ -4984,6 +5033,9 @@ class JiuWenClawDeepAdapter:
project_dir=inputs.get("project_dir"),
)
)
+ inputs = dict(inputs)
+ inputs["_invoke_turn_id"] = request.request_id
+ await self._sync_prompt_attachments_for_request(session_id, request.request_id)
result = await Runner.run_agent(agent=self._instance, inputs=inputs)
except asyncio.CancelledError:
logger.info(
@@ -4996,6 +5048,7 @@ class JiuWenClawDeepAdapter:
logger.error("[JiuWenClawDeepAdapter] Agent 任务执行异常: %s", e)
raise
finally:
+ await self._clear_prompt_attachments_for_request(session_id, request.request_id)
self._unregister_session_agent_task(session_id)
TOOL_PERMISSION_CHANNEL_ID.reset(token_cid)
cleanup_permission_context(token_perm)
@@ -5196,6 +5249,9 @@ class JiuWenClawDeepAdapter:
)
if self._stream_event_rail is not None:
self._stream_event_rail.reset_abort(session_id)
+ inputs = dict(inputs)
+ inputs["_invoke_turn_id"] = rid
+ await self._sync_prompt_attachments_for_request(session_id, rid)
async for chunk in Runner.run_agent_streaming(self._instance, inputs):
if not (hasattr(chunk, "type") and hasattr(chunk, "payload")):
parsed = self._parse_stream_chunk(chunk)
@@ -5415,6 +5471,7 @@ class JiuWenClawDeepAdapter:
is_complete=False,
)
finally:
+ await self._clear_prompt_attachments_for_request(session_id, rid)
self._unregister_session_agent_task(session_id)
TOOL_PERMISSION_CHANNEL_ID.reset(token_cid)
cleanup_permission_context(token_perm)
diff --git a/jiuwenswarm/server/runtime/prompt_attachment_loader.py b/jiuwenswarm/server/runtime/prompt_attachment_loader.py
new file mode 100644
index 0000000000..4f62d33e4a
--- /dev/null
+++ b/jiuwenswarm/server/runtime/prompt_attachment_loader.py
@@ -0,0 +1,1116 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Prompt attachment directory loader for jiuwenswarm."""
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import os
+import re
+import stat
+import threading
+import time
+from pathlib import Path
+from typing import Any, Iterable
+
+from openjiuwen.harness.prompts.prompt_attachment_manager import (
+ PromptAttachment,
+ PromptAttachmentKind,
+ PromptAttachmentScope,
+ PromptAttachmentUpdate,
+)
+
+
+logger = logging.getLogger(__name__)
+
+SESSION_SOURCE = "jiuwenswarm.prompt_attachment.session"
+TURN_SOURCE = "jiuwenswarm.prompt_attachment.turn"
+DEFAULT_MAX_FILE_CHARS = 12000
+_SAFE_SESSION_CHARS = re.compile(r"[^A-Za-z0-9_.-]+")
+_TEXT_SUFFIXES = frozenset({".md", ".txt"})
+_JSON_SUFFIX = ".json"
+_README_TEXT = """# Prompt Attachment
+
+Files in this directory are injected as dynamic prompt attachments for model calls.
+They are not user-uploaded attachments and are not written to long-term
+conversation history.
+
+Layout:
+- <session_id>/session/: session-scope prompt attachment files.
+- <session_id>/turn/<invoke_turn_id>/: request-scope prompt attachment
+ files, hot-loaded before each request.
+
+Markdown frontmatter is intentionally small: simple key-value fields and one
+level of metadata map are supported. Arrays, multiline strings, and full YAML
+features are not parsed by this loader.
+"""
+_KIND_BY_STEM = {
+ "runtime": PromptAttachmentKind.RUNTIME,
+ "request_context": PromptAttachmentKind.RUNTIME,
+ "diagnostics": PromptAttachmentKind.DIAGNOSTIC,
+ "memory_summary": PromptAttachmentKind.MEMORY,
+ "open_files": PromptAttachmentKind.FILE,
+}
+_USER_SOURCE = "jiuwenswarm.prompt_attachment.user"
+_LOCKS_GUARD = threading.Lock()
+_PATH_LOCKS: dict[str, threading.Lock] = {}
+
+
+def _is_relative_to(path: Path, root: Path) -> bool:
+ try:
+ path.relative_to(root)
+ return True
+ except ValueError:
+ return False
+
+
+def _is_reparse_path(path: Path) -> bool:
+ """Return True for symlink, junction, or other Windows reparse-point paths."""
+
+ if path.is_symlink():
+ return True
+ is_junction = getattr(path, "is_junction", None)
+ if callable(is_junction) and is_junction():
+ return True
+ try:
+ attrs = getattr(os.lstat(path), "st_file_attributes", 0)
+ except OSError:
+ return True
+ return bool(attrs & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))
+
+
+def _iter_safe_files(scope_dir: Path, suffixes: frozenset[str]) -> Iterable[Path]:
+ if not scope_dir.exists() or not scope_dir.is_dir():
+ return
+ scope_root = scope_dir.resolve()
+ pending = [scope_dir]
+ while pending:
+ current = pending.pop()
+ try:
+ entries = sorted(current.iterdir(), key=lambda item: item.as_posix())
+ except OSError as exc:
+ logger.warning("[PromptAttachmentLoader] failed to list prompt attachment directory %s: %s", current, exc)
+ continue
+ for path in entries:
+ try:
+ relative = path.relative_to(scope_dir)
+ except ValueError:
+ continue
+ if any(part.startswith(".") for part in relative.parts):
+ continue
+ if _is_reparse_path(path):
+ logger.warning("[PromptAttachmentLoader] skip linked prompt attachment path: %s", path)
+ continue
+ try:
+ resolved = path.resolve(strict=True)
+ except OSError as exc:
+ logger.warning("[PromptAttachmentLoader] failed to resolve prompt attachment path %s: %s", path, exc)
+ continue
+ if not _is_relative_to(resolved, scope_root):
+ logger.warning("[PromptAttachmentLoader] skip prompt attachment path outside scope: %s", path)
+ continue
+ if path.is_dir():
+ pending.append(path)
+ elif path.is_file() and path.suffix.lower() in suffixes:
+ yield path
+
+
+def _managed_source_for_scope(scope: PromptAttachmentScope) -> str:
+ return TURN_SOURCE if scope == PromptAttachmentScope.TURN else SESSION_SOURCE
+
+
+def _metadata_with_origin_source(metadata: dict[str, Any], origin_source: str | None) -> dict[str, Any]:
+ result = dict(metadata)
+ if origin_source and origin_source not in {SESSION_SOURCE, TURN_SOURCE}:
+ result.setdefault("origin_source", origin_source)
+ return result
+
+
+def sanitize_session_id(session_id: str | None) -> str:
+ """Return a deterministic path-safe session id."""
+
+ raw = str(session_id or "").strip()
+ if not raw:
+ return "default"
+ safe = _SAFE_SESSION_CHARS.sub("_", raw.replace("/", "_").replace("\\", "_")).strip("._-")
+ if not safe:
+ safe = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
+ if safe in {".", ".."}:
+ safe = f"session_{hashlib.sha256(raw.encode('utf-8')).hexdigest()[:16]}"
+ if len(safe) > 80:
+ digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:12]
+ safe = f"{safe[:67]}_{digest}"
+ return safe
+
+
+def _safe_id_part(value: str) -> str:
+ raw = str(value or "").strip()
+ safe = _SAFE_SESSION_CHARS.sub("_", raw).strip("._-")
+ if safe:
+ return safe
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:12]
+
+
+def _path_lock(path: Path) -> threading.Lock:
+ key = str(path.resolve())
+ with _LOCKS_GUARD:
+ lock = _PATH_LOCKS.get(key)
+ if lock is None:
+ lock = threading.Lock()
+ _PATH_LOCKS[key] = lock
+ return lock
+
+
+def _atomic_write_text(path: Path, text: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(f".{path.name}.tmp.{os.getpid()}.{threading.get_ident()}")
+ tmp.write_text(text, encoding="utf-8")
+ os.replace(tmp, path)
+
+
+def _kind_value(kind: PromptAttachmentKind | str) -> str:
+ return kind.value if isinstance(kind, PromptAttachmentKind) else str(kind)
+
+
+def _parse_scalar(value: str) -> Any:
+ stripped = value.strip()
+ if stripped in {"true", "True"}:
+ return True
+ if stripped in {"false", "False"}:
+ return False
+ if stripped in {"null", "None", "~"}:
+ return None
+ try:
+ return int(stripped)
+ except ValueError:
+ return stripped.strip('"').strip("'")
+
+
+def _parse_frontmatter(raw: str) -> tuple[dict[str, Any], str]:
+ if not raw.startswith("---\n") and not raw.startswith("---\r\n"):
+ return {}, raw
+ normalized = raw.replace("\r\n", "\n")
+ end = normalized.find("\n---\n", 4)
+ if end < 0:
+ return {}, raw
+ header = normalized[4:end]
+ body = normalized[end + len("\n---\n"):]
+ if body.startswith("\n"):
+ body = body[1:]
+ data: dict[str, Any] = {}
+ current_map: dict[str, Any] | None = None
+ for line in header.splitlines():
+ if not line.strip() or line.lstrip().startswith("#"):
+ continue
+ if line.startswith((" ", "\t")) and current_map is not None and ":" in line:
+ key, value = line.strip().split(":", 1)
+ current_map[key.strip()] = _parse_scalar(value)
+ continue
+ current_map = None
+ if ":" not in line:
+ continue
+ key, value = line.split(":", 1)
+ key = key.strip()
+ if value.strip():
+ data[key] = _parse_scalar(value)
+ else:
+ nested: dict[str, Any] = {}
+ data[key] = nested
+ current_map = nested
+ return data, body
+
+
+def _dump_frontmatter(data: dict[str, Any]) -> str:
+ lines = ["---"]
+ for key in sorted(data):
+ value = data[key]
+ if isinstance(value, dict):
+ lines.append(f"{key}:")
+ for nested_key in sorted(value):
+ lines.append(f" {nested_key}: {value[nested_key]}")
+ else:
+ lines.append(f"{key}: {value}")
+ lines.append("---")
+ return "\n".join(lines) + "\n\n"
+
+
+def _resolve_from_context(ctx: Any, *names: str) -> str | None:
+ for name in names:
+ value = getattr(ctx, name, None)
+ if value:
+ return str(value)
+ extra = getattr(ctx, "extra", None)
+ if isinstance(extra, dict):
+ for name in names:
+ value = extra.get(name)
+ if value:
+ return str(value)
+ request = getattr(ctx, "request", None)
+ if request is not None:
+ for name in names:
+ value = getattr(request, name, None)
+ if value:
+ return str(value)
+ session = getattr(ctx, "session", None)
+ if session is not None:
+ for name in names:
+ value = getattr(session, name, None)
+ if value:
+ return str(value)
+ return None
+
+
+class PromptAttachmentFileStore:
+ """User-friendly file CRUD for prompt attachment directories."""
+
+ def __init__(self, root: Path | str, *, max_file_chars: int = DEFAULT_MAX_FILE_CHARS) -> None:
+ self.root = Path(root)
+ self.max_file_chars = max_file_chars
+
+ def for_context(self, ctx: Any) -> "PromptAttachmentContextStore":
+ return PromptAttachmentContextStore(self, ctx)
+
+ def for_session(self, session_id: str, *, invoke_turn_id: str | None = None) -> "PromptAttachmentSessionStore":
+ return PromptAttachmentSessionStore(self, session_id=session_id, invoke_turn_id=invoke_turn_id)
+
+ def add_markdown(
+ self,
+ *,
+ session_id: str,
+ content: str,
+ scope: PromptAttachmentScope | str = PromptAttachmentScope.SESSION,
+ invoke_turn_id: str | None = None,
+ name: str | None = None,
+ priority: int = 0,
+ kind: PromptAttachmentKind | str = PromptAttachmentKind.TEXT,
+ source: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ ) -> PromptAttachment:
+ path = self._file_path(
+ session_id=session_id,
+ scope=scope,
+ invoke_turn_id=invoke_turn_id,
+ name=name,
+ suffix=".md",
+ )
+ if path.exists():
+ raise FileExistsError(f"prompt attachment already exists: {path}")
+ frontmatter = self._frontmatter(
+ priority=priority,
+ kind=kind,
+ source=source or _USER_SOURCE,
+ metadata=metadata,
+ )
+ with _path_lock(path):
+ _atomic_write_text(path, _dump_frontmatter(frontmatter) + content)
+ return self._item_from_file(path, session_id=session_id, scope=scope, invoke_turn_id=invoke_turn_id)
+
+ def update_markdown(
+ self,
+ id_or_name: str,
+ *,
+ session_id: str,
+ scope: PromptAttachmentScope | str = PromptAttachmentScope.SESSION,
+ invoke_turn_id: str | None = None,
+ content: str | None = None,
+ priority: int | None = None,
+ source: str | None = None,
+ kind: PromptAttachmentKind | str | None = None,
+ metadata: dict[str, Any] | None = None,
+ metadata_replace: bool = False,
+ replace: bool = False,
+ ) -> PromptAttachment:
+ path = self._resolve_id_or_name(
+ id_or_name,
+ session_id=session_id,
+ scope=scope,
+ invoke_turn_id=invoke_turn_id,
+ include_json=False,
+ )
+ if path is None:
+ raise FileNotFoundError(f"prompt attachment does not exist: {id_or_name}")
+ with _path_lock(path):
+ old_meta, old_content = _parse_frontmatter(path.read_text(encoding="utf-8"))
+ next_meta = {} if replace else dict(old_meta)
+ if priority is not None:
+ next_meta["priority"] = priority
+ if source is not None:
+ next_meta["source"] = source
+ if kind is not None:
+ next_meta["kind"] = _kind_value(self._coerce_kind(kind))
+ if metadata is not None:
+ if metadata_replace:
+ next_meta["metadata"] = dict(metadata)
+ else:
+ next_meta["metadata"] = {**dict(next_meta.get("metadata") or {}), **metadata}
+ next_content = old_content if content is None else content
+ _atomic_write_text(path, _dump_frontmatter(next_meta) + next_content)
+ return self._item_from_file(path, session_id=session_id, scope=scope, invoke_turn_id=invoke_turn_id)
+
+ def add(self, prompt_attachment: PromptAttachment) -> PromptAttachment:
+ path = self._json_path(prompt_attachment)
+ if path.exists():
+ raise FileExistsError(f"prompt attachment already exists: {prompt_attachment.id}")
+ with _path_lock(path):
+ _atomic_write_text(
+ path,
+ json.dumps(
+ prompt_attachment.model_dump(exclude_none=True),
+ ensure_ascii=False,
+ indent=2,
+ sort_keys=True,
+ )
+ + "\n",
+ )
+ return prompt_attachment.model_copy(deep=True)
+
+ def update(
+ self,
+ prompt_attachment_id: str,
+ update: PromptAttachmentUpdate,
+ *,
+ metadata_replace: bool = False,
+ ) -> PromptAttachment:
+ path, current = self._find_json(prompt_attachment_id)
+ if path is None or current is None:
+ raise FileNotFoundError(f"prompt attachment does not exist: {prompt_attachment_id}")
+ with _path_lock(path):
+ data = current.model_dump()
+ patch = update.model_dump(exclude_unset=True)
+ if "metadata" in patch and not metadata_replace:
+ patch["metadata"] = {
+ **dict(data.get("metadata") or {}),
+ **dict(patch.get("metadata") or {}),
+ }
+ data.update(patch)
+ updated = PromptAttachment(**data)
+ next_path = self._json_path(updated)
+ _atomic_write_text(
+ next_path,
+ json.dumps(updated.model_dump(exclude_none=True), ensure_ascii=False, indent=2, sort_keys=True) + "\n",
+ )
+ if next_path != path:
+ path.unlink()
+ return updated
+
+ def get(
+ self,
+ id_or_name: str,
+ *,
+ session_id: str,
+ scope: PromptAttachmentScope | str = PromptAttachmentScope.SESSION,
+ invoke_turn_id: str | None = None,
+ ) -> PromptAttachment | None:
+ path = self._resolve_id_or_name(
+ id_or_name,
+ session_id=session_id,
+ scope=scope,
+ invoke_turn_id=invoke_turn_id,
+ )
+ if path is None:
+ return None
+ return self._item_from_file(path, session_id=session_id, scope=scope, invoke_turn_id=invoke_turn_id)
+
+ def delete(
+ self,
+ id_or_name: str,
+ *,
+ session_id: str,
+ scope: PromptAttachmentScope | str = PromptAttachmentScope.SESSION,
+ invoke_turn_id: str | None = None,
+ ) -> bool:
+ path = self._resolve_id_or_name(
+ id_or_name,
+ session_id=session_id,
+ scope=scope,
+ invoke_turn_id=invoke_turn_id,
+ )
+ if path is None:
+ return False
+ with _path_lock(path):
+ if not path.exists():
+ return False
+ path.unlink()
+ return True
+
+ def list(
+ self,
+ *,
+ session_id: str,
+ scope: PromptAttachmentScope | str | None = None,
+ invoke_turn_id: str | None = None,
+ ) -> list[PromptAttachment]:
+ scopes = [self._coerce_scope(scope)] if scope is not None else [
+ PromptAttachmentScope.SESSION,
+ PromptAttachmentScope.TURN,
+ ]
+ items: list[PromptAttachment] = []
+ for scope_value in scopes:
+ for scope_dir, turn_id in self._list_scope_dirs(
+ session_id=session_id,
+ scope=scope_value,
+ invoke_turn_id=invoke_turn_id,
+ ):
+ if not scope_dir.exists():
+ continue
+ for path in _iter_safe_files(scope_dir, _TEXT_SUFFIXES | {_JSON_SUFFIX}):
+ item = self._item_from_file(
+ path,
+ session_id=session_id,
+ scope=scope_value,
+ invoke_turn_id=turn_id,
+ )
+ items.append(item)
+ return items
+
+ def _list_scope_dirs(
+ self,
+ *,
+ session_id: str,
+ scope: PromptAttachmentScope,
+ invoke_turn_id: str | None,
+ ) -> list[tuple[Path, str | None]]:
+ if scope == PromptAttachmentScope.SESSION:
+ return [(self._scope_dir(session_id, scope=scope, invoke_turn_id=None), None)]
+ if invoke_turn_id:
+ return [(self._scope_dir(session_id, scope=scope, invoke_turn_id=invoke_turn_id), invoke_turn_id)]
+ turn_root = self.root / sanitize_session_id(session_id) / "turn"
+ if not turn_root.exists():
+ return []
+ return [
+ (path, path.name)
+ for path in sorted(turn_root.iterdir(), key=lambda item: item.as_posix())
+ if path.is_dir() and not path.name.startswith(".")
+ ]
+
+ def _item_from_file(
+ self,
+ path: Path,
+ *,
+ session_id: str,
+ scope: PromptAttachmentScope | str,
+ invoke_turn_id: str | None,
+ ) -> PromptAttachment:
+ scope_value = self._coerce_scope(scope)
+ if path.suffix.lower() == _JSON_SUFFIX:
+ item = PromptAttachment(**json.loads(path.read_text(encoding="utf-8")))
+ metadata = _metadata_with_origin_source(dict(item.metadata or {}), item.source)
+ return item.model_copy(update={
+ "source": _managed_source_for_scope(scope_value),
+ "metadata": metadata,
+ })
+ scope_dir = self._scope_dir(session_id, scope=scope_value, invoke_turn_id=invoke_turn_id)
+ meta, content = _parse_frontmatter(path.read_text(encoding="utf-8"))
+ item_id = self._id_from_path(
+ path,
+ scope_dir,
+ session_id=session_id,
+ scope=scope_value,
+ invoke_turn_id=invoke_turn_id,
+ )
+ metadata = _metadata_with_origin_source(dict(meta.get("metadata") or {}), meta.get("source"))
+ metadata.update({"path": str(path), "relative_path": path.relative_to(scope_dir).as_posix()})
+ return PromptAttachment(
+ id=item_id,
+ scope=scope_value,
+ kind=meta.get("kind") or PromptAttachmentLoader.kind_for_file(path),
+ content=content,
+ priority=int(meta.get("priority") or 0),
+ source=_managed_source_for_scope(scope_value),
+ session_id=session_id,
+ invoke_turn_id=invoke_turn_id if scope_value == PromptAttachmentScope.TURN else None,
+ metadata=metadata,
+ content_kind="text/markdown" if path.suffix.lower() == ".md" else "text/plain",
+ )
+
+ def _resolve_id_or_name(
+ self,
+ id_or_name: str,
+ *,
+ session_id: str,
+ scope: PromptAttachmentScope | str,
+ invoke_turn_id: str | None,
+ include_json: bool = True,
+ ) -> Path | None:
+ scope_value = self._coerce_scope(scope)
+ scope_dir = self._scope_dir(session_id, scope=scope_value, invoke_turn_id=invoke_turn_id)
+ suffixes = _TEXT_SUFFIXES | ({_JSON_SUFFIX} if include_json else frozenset())
+ try:
+ name_path = self._safe_relative_file_name(name=id_or_name, suffix=".md")
+ candidate = scope_dir / name_path
+ if candidate.suffix.lower() in suffixes and candidate.exists():
+ return candidate
+ except ValueError:
+ pass
+ for path in _iter_safe_files(scope_dir, suffixes):
+ item_id = self._id_from_path(
+ path,
+ scope_dir,
+ session_id=session_id,
+ scope=scope_value,
+ invoke_turn_id=invoke_turn_id,
+ )
+ if item_id == id_or_name:
+ return path
+ if not include_json:
+ return None
+ json_path, _ = self._find_json(
+ id_or_name,
+ session_id=session_id,
+ scope=scope_value,
+ invoke_turn_id=invoke_turn_id,
+ )
+ return json_path
+
+ def _file_path(
+ self,
+ *,
+ session_id: str,
+ scope: PromptAttachmentScope | str,
+ invoke_turn_id: str | None,
+ name: str | None,
+ suffix: str,
+ ) -> Path:
+ scope_value = self._coerce_scope(scope)
+ if name is None:
+ name = f"auto_{time.time_ns()}_{threading.get_ident()}{suffix}"
+ return self._scope_dir(
+ session_id,
+ scope=scope_value,
+ invoke_turn_id=invoke_turn_id,
+ ) / self._safe_relative_file_name(
+ name=name, suffix=suffix,
+ )
+
+ def _scope_dir(
+ self,
+ session_id: str,
+ *,
+ scope: PromptAttachmentScope,
+ invoke_turn_id: str | None,
+ ) -> Path:
+ safe_session_id = sanitize_session_id(session_id)
+ if scope == PromptAttachmentScope.TURN:
+ if not invoke_turn_id:
+ raise ValueError("invoke_turn_id is required for turn-scope prompt attachments")
+ return self.root / safe_session_id / "turn" / _safe_id_part(invoke_turn_id)
+ return self.root / safe_session_id / "session"
+
+ @staticmethod
+ def _frontmatter(
+ *,
+ priority: int,
+ kind: PromptAttachmentKind | str,
+ source: str,
+ metadata: dict[str, Any] | None,
+ ) -> dict[str, Any]:
+ data: dict[str, Any] = {
+ "kind": _kind_value(kind),
+ "priority": priority,
+ "source": source,
+ }
+ if metadata:
+ data["metadata"] = dict(metadata)
+ return data
+
+ @staticmethod
+ def _id_from_path(
+ path: Path,
+ scope_dir: Path,
+ *,
+ session_id: str,
+ scope: PromptAttachmentScope,
+ invoke_turn_id: str | None,
+ ) -> str:
+ relative_key = PromptAttachmentLoader.relative_key(path, scope_dir)
+ safe_session_id = sanitize_session_id(session_id)
+ if scope == PromptAttachmentScope.TURN:
+ return f"{scope.value}.{safe_session_id}.{_safe_id_part(invoke_turn_id or 'turn')}.{relative_key}"
+ return f"{scope.value}.{safe_session_id}.{relative_key}"
+
+ def _json_path(self, prompt_attachment: PromptAttachment) -> Path:
+ scope = self._coerce_scope(prompt_attachment.scope)
+ return self._scope_dir(
+ prompt_attachment.session_id or "default",
+ scope=scope,
+ invoke_turn_id=prompt_attachment.invoke_turn_id,
+ ) / f"{_safe_id_part(prompt_attachment.id)}{_JSON_SUFFIX}"
+
+ def _find_json(
+ self,
+ prompt_attachment_id: str,
+ *,
+ session_id: str | None = None,
+ scope: PromptAttachmentScope | str | None = None,
+ invoke_turn_id: str | None = None,
+ ) -> tuple[Path | None, PromptAttachment | None]:
+ file_name = f"{_safe_id_part(prompt_attachment_id)}{_JSON_SUFFIX}"
+ if session_id is not None and scope is not None:
+ scope_value = self._coerce_scope(scope)
+ search_dirs = []
+ for scope_dir, _ in self._list_scope_dirs(
+ session_id=session_id,
+ scope=scope_value,
+ invoke_turn_id=invoke_turn_id,
+ ):
+ search_dirs.append(scope_dir)
+ elif session_id is not None:
+ search_dirs = []
+ for scope_value in (PromptAttachmentScope.SESSION, PromptAttachmentScope.TURN):
+ turn_id = invoke_turn_id if scope_value == PromptAttachmentScope.TURN else None
+ for scope_dir, _ in self._list_scope_dirs(
+ session_id=session_id,
+ scope=scope_value,
+ invoke_turn_id=turn_id,
+ ):
+ search_dirs.append(scope_dir)
+ else:
+ search_dirs = [self.root]
+ for search_dir in search_dirs:
+ for path in _iter_safe_files(search_dir, frozenset({_JSON_SUFFIX})):
+ if path.name != file_name:
+ continue
+ item = PromptAttachment(**json.loads(path.read_text(encoding="utf-8")))
+ if item.id == prompt_attachment_id:
+ return path, item
+ return None, None
+
+ @staticmethod
+ def coerce_scope(scope: PromptAttachmentScope | str) -> PromptAttachmentScope:
+ return scope if isinstance(scope, PromptAttachmentScope) else PromptAttachmentScope(str(scope))
+
+ @staticmethod
+ def _coerce_scope(scope: PromptAttachmentScope | str) -> PromptAttachmentScope:
+ return PromptAttachmentFileStore.coerce_scope(scope)
+
+ @staticmethod
+ def _coerce_kind(kind: PromptAttachmentKind | str) -> PromptAttachmentKind:
+ return kind if isinstance(kind, PromptAttachmentKind) else PromptAttachmentKind(str(kind))
+
+ @staticmethod
+ def _safe_relative_file_name(*, name: str, suffix: str) -> Path:
+ raw_name = str(name or "").strip()
+ raw_path = Path(raw_name if Path(raw_name).suffix else f"{raw_name}{suffix}")
+ if raw_path.is_absolute() or any(part in {"", ".", ".."} for part in raw_path.parts):
+ raise ValueError(f"unsafe prompt attachment file name: {name}")
+ if any(part.startswith(".") for part in raw_path.parts):
+ raise ValueError(f"hidden prompt attachment file names are not supported: {name}")
+ if raw_path.suffix.lower() not in (_TEXT_SUFFIXES | {_JSON_SUFFIX}):
+ raise ValueError(f"unsupported prompt attachment file suffix: {raw_path.suffix}")
+ return Path(*[
+ (
+ f"{_safe_id_part(Path(part).stem)}{Path(part).suffix.lower()}"
+ if index == len(raw_path.parts) - 1
+ else _safe_id_part(part)
+ )
+ for index, part in enumerate(raw_path.parts)
+ ])
+
+
+class PromptAttachmentContextStore:
+ """Context-bound writer that hides session and turn ids from callers."""
+
+ def __init__(self, store: PromptAttachmentFileStore, ctx: Any) -> None:
+ self._store = store
+ self.session_id = _resolve_from_context(ctx, "session_id", "_session_id", "id") or "default"
+ self.invoke_turn_id = _resolve_from_context(
+ ctx,
+ "invoke_turn_id",
+ "_invoke_turn_id",
+ "request_id",
+ "rid",
+ )
+
+ def add_markdown(self, **kwargs: Any) -> PromptAttachment:
+ scope = kwargs.get("scope", PromptAttachmentScope.TURN)
+ if PromptAttachmentFileStore.coerce_scope(scope) == PromptAttachmentScope.TURN and not self.invoke_turn_id:
+ raise ValueError(
+ "No active invoke_turn_id is bound. Use for_session(...).add_turn_markdown or pass context."
+ )
+ kwargs.setdefault("scope", scope)
+ return self._store.add_markdown(
+ session_id=self.session_id,
+ invoke_turn_id=self.invoke_turn_id,
+ **kwargs,
+ )
+
+ def update_markdown(self, id_or_name: str, **kwargs: Any) -> PromptAttachment:
+ self._bind_turn_id_if_needed(kwargs)
+ return self._store.update_markdown(id_or_name, session_id=self.session_id, **kwargs)
+
+ def get(self, id_or_name: str, **kwargs: Any) -> PromptAttachment | None:
+ self._bind_turn_id_if_needed(kwargs)
+ return self._store.get(id_or_name, session_id=self.session_id, **kwargs)
+
+ def delete(self, id_or_name: str, **kwargs: Any) -> bool:
+ self._bind_turn_id_if_needed(kwargs)
+ return self._store.delete(id_or_name, session_id=self.session_id, **kwargs)
+
+ def list(self, **kwargs: Any) -> list[PromptAttachment]:
+ self._bind_turn_id_if_needed(kwargs)
+ return self._store.list(session_id=self.session_id, **kwargs)
+
+ def _bind_turn_id_if_needed(self, kwargs: dict[str, Any]) -> None:
+ scope = kwargs.get("scope")
+ if scope is None or PromptAttachmentFileStore.coerce_scope(scope) != PromptAttachmentScope.TURN:
+ return
+ if kwargs.get("invoke_turn_id"):
+ return
+ if not self.invoke_turn_id:
+ raise ValueError("No active invoke_turn_id is bound. Pass invoke_turn_id explicitly.")
+ kwargs["invoke_turn_id"] = self.invoke_turn_id
+
+
+class PromptAttachmentSessionStore:
+ """Session-bound writer for services that know session_id but not full ctx."""
+
+ def __init__(self, store: PromptAttachmentFileStore, *, session_id: str, invoke_turn_id: str | None = None) -> None:
+ self._store = store
+ self.session_id = session_id
+ self.invoke_turn_id = invoke_turn_id
+
+ def add_session_markdown(self, **kwargs: Any) -> PromptAttachment:
+ return self._store.add_markdown(
+ session_id=self.session_id,
+ scope=PromptAttachmentScope.SESSION,
+ **kwargs,
+ )
+
+ def add_turn_markdown(self, *, invoke_turn_id: str | None = None, **kwargs: Any) -> PromptAttachment:
+ turn_id = invoke_turn_id or self.invoke_turn_id
+ if not turn_id:
+ raise ValueError("No active invoke_turn_id is bound. Pass invoke_turn_id explicitly.")
+ return self._store.add_markdown(
+ session_id=self.session_id,
+ invoke_turn_id=turn_id,
+ scope=PromptAttachmentScope.TURN,
+ **kwargs,
+ )
+
+ def add_current_turn_markdown(self, **kwargs: Any) -> PromptAttachment:
+ return self.add_turn_markdown(**kwargs)
+
+ def update_markdown(self, id_or_name: str, **kwargs: Any) -> PromptAttachment:
+ self._bind_turn_id_if_needed(kwargs)
+ return self._store.update_markdown(id_or_name, session_id=self.session_id, **kwargs)
+
+ def get(self, id_or_name: str, **kwargs: Any) -> PromptAttachment | None:
+ self._bind_turn_id_if_needed(kwargs)
+ return self._store.get(id_or_name, session_id=self.session_id, **kwargs)
+
+ def delete(self, id_or_name: str, **kwargs: Any) -> bool:
+ self._bind_turn_id_if_needed(kwargs)
+ return self._store.delete(id_or_name, session_id=self.session_id, **kwargs)
+
+ def list(self, **kwargs: Any) -> list[PromptAttachment]:
+ self._bind_turn_id_if_needed(kwargs)
+ return self._store.list(session_id=self.session_id, **kwargs)
+
+ def _bind_turn_id_if_needed(self, kwargs: dict[str, Any]) -> None:
+ scope = kwargs.get("scope")
+ if scope is None or PromptAttachmentFileStore.coerce_scope(scope) != PromptAttachmentScope.TURN:
+ return
+ if kwargs.get("invoke_turn_id"):
+ return
+ if not self.invoke_turn_id:
+ raise ValueError("No active invoke_turn_id is bound. Pass invoke_turn_id explicitly.")
+ kwargs["invoke_turn_id"] = self.invoke_turn_id
+
+
+class PromptAttachmentLoader:
+ """Load jiuwenswarm prompt attachment files into a DeepAgent manager."""
+
+ def __init__(self, root: Path | str, *, max_file_chars: int = DEFAULT_MAX_FILE_CHARS) -> None:
+ self.root = Path(root)
+ self.max_file_chars = max_file_chars
+ self.file_store = PromptAttachmentFileStore(self.root, max_file_chars=max_file_chars)
+
+ def for_context(self, ctx: Any) -> PromptAttachmentContextStore:
+ """Return a context-bound file writer facade."""
+
+ return self.file_store.for_context(ctx)
+
+ def for_session(self, session_id: str, *, invoke_turn_id: str | None = None) -> PromptAttachmentSessionStore:
+ """Return a session-bound file writer facade."""
+
+ return self.file_store.for_session(session_id, invoke_turn_id=invoke_turn_id)
+
+ def ensure_layout(self) -> None:
+ """Create the root prompt attachment layout."""
+
+ self.root.mkdir(parents=True, exist_ok=True)
+ readme = self.root / "README.md"
+ should_write_readme = True
+ if readme.exists():
+ try:
+ current = readme.read_text(encoding="utf-8")
+ should_write_readme = current != _README_TEXT or any(ord(char) >= 128 for char in current)
+ except UnicodeDecodeError:
+ should_write_readme = True
+ if should_write_readme:
+ readme.write_text(_README_TEXT, encoding="utf-8")
+
+ def load_session_attachments(self, session_id: str) -> list[PromptAttachment]:
+ """Load session-scope prompt attachments for one jiuwenswarm session."""
+
+ safe_session_id = sanitize_session_id(session_id)
+ scope_dir = self.root / safe_session_id / "session"
+ return self._load_scope_dir(
+ scope_dir,
+ scope=PromptAttachmentScope.SESSION,
+ source=SESSION_SOURCE,
+ session_id=session_id,
+ safe_session_id=safe_session_id,
+ )
+
+ def load_turn_attachments(self, session_id: str, invoke_turn_id: str) -> list[PromptAttachment]:
+ """Load turn-scope prompt attachments for one user request."""
+
+ safe_session_id = sanitize_session_id(session_id)
+ turn_root = self.root / safe_session_id / "turn"
+ safe_turn_id = _safe_id_part(invoke_turn_id or "turn")
+ return self._load_scope_dir(
+ turn_root / safe_turn_id,
+ scope=PromptAttachmentScope.TURN,
+ source=TURN_SOURCE,
+ session_id=session_id,
+ safe_session_id=safe_session_id,
+ invoke_turn_id=invoke_turn_id,
+ )
+
+ async def sync_to_agent(
+ self,
+ agent: Any,
+ *,
+ session_id: str,
+ invoke_turn_id: str,
+ ) -> None:
+ """Synchronize current prompt attachment files to a DeepAgent instance.
+
+ Loader failures are intentionally non-fatal. User requests must continue
+ even if one prompt attachment file is unreadable.
+ """
+
+ try:
+ manager = getattr(agent, "prompt_attachment_manager", None)
+ if manager is None:
+ raise AttributeError("agent.prompt_attachment_manager is unavailable")
+ except Exception as exc:
+ logger.warning("[PromptAttachmentLoader] failed to get PromptAttachmentManager: %s", exc)
+ return
+
+ try:
+ # Clear only this request's old turn attachments. Clearing the whole
+ # session would make concurrent requests remove each other's
+ # request-local attachments.
+ await manager.remove_by_filter(
+ source=TURN_SOURCE,
+ session_id=session_id,
+ invoke_turn_id=invoke_turn_id,
+ scope=PromptAttachmentScope.TURN,
+ )
+ except Exception as exc:
+ logger.warning("[PromptAttachmentLoader] failed to clear old turn prompt attachments: %s", exc)
+
+ try:
+ session_attachments = self.load_session_attachments(session_id)
+ turn_attachments = self.load_turn_attachments(session_id, invoke_turn_id)
+ except Exception as exc:
+ logger.warning("[PromptAttachmentLoader] failed to load prompt attachment directory: %s", exc)
+ return
+ logger.info(
+ "[PromptAttachmentLoader] sync prompt attachments: session_id=%s invoke_turn_id=%s session=%d turn=%d",
+ session_id,
+ invoke_turn_id,
+ len(session_attachments),
+ len(turn_attachments),
+ )
+
+ try:
+ await manager.replace_source(
+ source=SESSION_SOURCE,
+ prompt_attachments=session_attachments,
+ session_id=session_id,
+ scope=PromptAttachmentScope.SESSION,
+ )
+ except Exception as exc:
+ logger.warning("[PromptAttachmentLoader] failed to sync session prompt attachments: %s", exc)
+
+ try:
+ await manager.replace_source(
+ source=TURN_SOURCE,
+ prompt_attachments=turn_attachments,
+ session_id=session_id,
+ invoke_turn_id=invoke_turn_id,
+ scope=PromptAttachmentScope.TURN,
+ )
+ except Exception as exc:
+ logger.warning("[PromptAttachmentLoader] failed to sync turn prompt attachments: %s", exc)
+
+ @staticmethod
+ async def clear_turn_from_agent(
+ agent: Any,
+ *,
+ session_id: str,
+ invoke_turn_id: str,
+ ) -> None:
+ """Remove prompt attachments loaded for one completed request."""
+
+ try:
+ manager = getattr(agent, "prompt_attachment_manager", None)
+ if manager is None:
+ raise AttributeError("agent.prompt_attachment_manager is unavailable")
+ # Request cleanup must stay scoped by invoke_turn_id for concurrent
+ # requests in the same session.
+ await manager.remove_by_filter(
+ source=TURN_SOURCE,
+ session_id=session_id,
+ invoke_turn_id=invoke_turn_id,
+ scope=PromptAttachmentScope.TURN,
+ )
+ except Exception as exc:
+ logger.warning("[PromptAttachmentLoader] failed to clear completed turn prompt attachments: %s", exc)
+
+ def _load_scope_dir(
+ self,
+ scope_dir: Path,
+ *,
+ scope: PromptAttachmentScope,
+ source: str,
+ session_id: str,
+ safe_session_id: str,
+ invoke_turn_id: str | None = None,
+ ) -> list[PromptAttachment]:
+ if not scope_dir.exists():
+ return []
+ if not scope_dir.is_dir():
+ logger.warning("[PromptAttachmentLoader] prompt attachment scope path is not a directory: %s", scope_dir)
+ return []
+
+ items: list[PromptAttachment] = []
+ for path in self._iter_attachment_files(scope_dir):
+ try:
+ if path.suffix.lower() == _JSON_SUFFIX:
+ item = self._read_json_file(
+ path,
+ scope_dir,
+ scope=scope,
+ source=source,
+ session_id=session_id,
+ invoke_turn_id=invoke_turn_id,
+ )
+ if item is not None:
+ items.append(item)
+ continue
+ content = self._read_text_file(path, scope_dir)
+ except Exception as exc:
+ logger.warning("[PromptAttachmentLoader] failed to read prompt attachment file %s: %s", path, exc)
+ continue
+ if content is None:
+ continue
+ meta, content = _parse_frontmatter(content)
+ metadata = _metadata_with_origin_source(dict(meta.get("metadata") or {}), meta.get("source"))
+ metadata.update({"path": str(path), "relative_path": path.relative_to(scope_dir).as_posix()})
+ relative_key = self._relative_key(path, scope_dir)
+ if scope == PromptAttachmentScope.TURN:
+ safe_turn_id = _safe_id_part(invoke_turn_id or "turn")
+ item_id = f"{scope.value}.{safe_session_id}.{safe_turn_id}.{relative_key}"
+ else:
+ item_id = f"{scope.value}.{safe_session_id}.{relative_key}"
+ items.append(PromptAttachment(
+ id=item_id,
+ scope=scope,
+ kind=meta.get("kind") or self._kind_for_file(path),
+ content=content,
+ priority=int(meta.get("priority") or 0),
+ source=source,
+ session_id=session_id,
+ invoke_turn_id=invoke_turn_id if scope == PromptAttachmentScope.TURN else None,
+ metadata=metadata,
+ content_kind="text/markdown" if path.suffix.lower() == ".md" else "text/plain",
+ ))
+ return items
+
+ @staticmethod
+ def _iter_attachment_files(scope_dir: Path) -> Iterable[Path]:
+ files = list(_iter_safe_files(scope_dir, _TEXT_SUFFIXES | {_JSON_SUFFIX}))
+ return sorted(files, key=lambda path: path.relative_to(scope_dir).as_posix())
+
+ @staticmethod
+ def _read_json_file(
+ path: Path,
+ scope_dir: Path,
+ *,
+ scope: PromptAttachmentScope,
+ source: str,
+ session_id: str,
+ invoke_turn_id: str | None,
+ ) -> PromptAttachment | None:
+ raw = path.read_text(encoding="utf-8")
+ if not raw.strip():
+ logger.debug(
+ "[PromptAttachmentLoader] skip empty prompt attachment file: %s",
+ path.relative_to(scope_dir).as_posix(),
+ )
+ return None
+ item = PromptAttachment(**json.loads(raw))
+ if item.scope != scope:
+ logger.warning("[PromptAttachmentLoader] skip prompt attachment with mismatched scope: %s", path)
+ return None
+ metadata = _metadata_with_origin_source(dict(item.metadata or {}), item.source)
+ metadata.update({"path": str(path), "relative_path": path.relative_to(scope_dir).as_posix()})
+ return item.model_copy(update={
+ "source": source,
+ "session_id": item.session_id or session_id,
+ "invoke_turn_id": invoke_turn_id if scope == PromptAttachmentScope.TURN else None,
+ "metadata": metadata,
+ })
+
+ def _read_text_file(self, path: Path, scope_dir: Path) -> str | None:
+ text = path.read_text(encoding="utf-8")
+ if not text.strip():
+ logger.debug(
+ "[PromptAttachmentLoader] skip empty prompt attachment file: %s",
+ path.relative_to(scope_dir).as_posix(),
+ )
+ return None
+ if self.max_file_chars > 0 and len(text) > self.max_file_chars:
+ original_chars = len(text)
+ text = text[:self.max_file_chars] + "\n\n[Prompt attachment file truncated by jiuwenswarm loader.]"
+ logger.warning(
+ "[PromptAttachmentLoader] truncated prompt attachment file: "
+ "path=%s original_chars=%s truncated_chars=%s",
+ path.relative_to(scope_dir).as_posix(),
+ original_chars,
+ len(text),
+ )
+ return text
+
+ @staticmethod
+ def kind_for_file(path: Path) -> PromptAttachmentKind:
+ return _KIND_BY_STEM.get(path.stem, PromptAttachmentKind.TEXT)
+
+ @staticmethod
+ def _kind_for_file(path: Path) -> PromptAttachmentKind:
+ return PromptAttachmentLoader.kind_for_file(path)
+
+ @staticmethod
+ def relative_key(path: Path, scope_dir: Path) -> str:
+ rel = path.relative_to(scope_dir).with_suffix("")
+ return ".".join(_safe_id_part(part) for part in rel.parts)
+
+ @staticmethod
+ def _relative_key(path: Path, scope_dir: Path) -> str:
+ return PromptAttachmentLoader.relative_key(path, scope_dir)
+
+
+__all__ = [
+ "DEFAULT_MAX_FILE_CHARS",
+ "PromptAttachmentContextStore",
+ "PromptAttachmentFileStore",
+ "PromptAttachmentLoader",
+ "PromptAttachmentSessionStore",
+ "SESSION_SOURCE",
+ "TURN_SOURCE",
+ "sanitize_session_id",
+]
diff --git a/tests/system_tests/test_project_memory.py b/tests/system_tests/test_project_memory.py
index 100d968273..560ea0ac28 100644
--- a/tests/system_tests/test_project_memory.py
+++ b/tests/system_tests/test_project_memory.py
@@ -10,14 +10,16 @@ from __future__ import annotations
import os
import tempfile
from pathlib import Path
+from types import SimpleNamespace
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 JiuwenClawCodeAdapter
from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenClawDeepAdapter
from jiuwenswarm.agents.harness.common.rails.project_memory import (
- SECTION_NAME,
clear_project_memory_cache,
discover_and_load_memory_files,
merge_memory_content,
@@ -59,9 +61,30 @@ 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
+def _make_ctx(agent: MagicMock, session_id: str = "sess1") -> SimpleNamespace:
+ return SimpleNamespace(
+ agent=agent,
+ session=SimpleNamespace(session_id=session_id),
+ inputs=SimpleNamespace(),
+ extra={},
+ )
+
+
+async def _project_memory_attachment(agent: MagicMock, session_id: str = "sess1"):
+ items = await agent.prompt_attachment_manager.collect_for_turn(session_id, "turn1")
+ 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_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 ""
+
+
@pytest.fixture(autouse=True)
def _clear_cache():
clear_project_memory_cache()
@@ -86,14 +109,12 @@ class TestProjectMemoryRailEndToEnd:
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- sections = agent.system_prompt_builder.added_sections
- assert sections
- section = sections[-1]
- assert section.name == SECTION_NAME
- assert "PROJECT-RULE-1" in section.content["en"]
- assert "PROJECT-RULE-1" in section.content["cn"]
+ section = await _project_memory_attachment(agent)
+ assert section is not None
+ assert section.id == "session.sess1.project_memory"
+ assert "PROJECT-RULE-1" in section.content
@pytest.mark.asyncio
async def test_rail_reloads_after_file_change(self):
@@ -105,14 +126,14 @@ class TestProjectMemoryRailEndToEnd:
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
- body1 = agent.system_prompt_builder.added_sections[-1].content["en"]
+ await rail.before_model_call(ctx=_make_ctx(agent))
+ body1 = await _project_memory_body(agent)
assert "VERSION-1" in body1
_touch(root, "JIUWENSWARM.md", "VERSION-2")
clear_project_memory_cache(str(root))
- await rail.before_model_call(ctx=MagicMock())
- body2 = agent.system_prompt_builder.added_sections[-1].content["en"]
+ await rail.before_model_call(ctx=_make_ctx(agent))
+ body2 = await _project_memory_body(agent)
assert "VERSION-2" in body2
assert "VERSION-1" not in body2
@@ -126,14 +147,11 @@ class TestProjectMemoryRailEndToEnd:
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
- assert agent.system_prompt_builder.added_sections
+ await rail.before_model_call(ctx=_make_ctx(agent))
+ assert await _project_memory_attachment(agent) is not None
rail.uninit(agent)
- assert [
- s for s in agent.system_prompt_builder.added_sections
- if s.name == SECTION_NAME
- ] == []
+ assert rail.attachment_manager is None
@pytest.mark.asyncio
async def test_rail_no_section_when_workspace_empty(self):
@@ -144,13 +162,9 @@ class TestProjectMemoryRailEndToEnd:
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- project_sections = [
- s for s in agent.system_prompt_builder.added_sections
- if s.name == SECTION_NAME
- ]
- assert project_sections == []
+ assert await _project_memory_attachment(agent) is None
@pytest.mark.asyncio
async def test_rail_additional_directories_via_env(self, monkeypatch):
@@ -173,9 +187,9 @@ class TestProjectMemoryRailEndToEnd:
)
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent)
assert "EXTRA-PROJECT-RULE" in body
@@ -610,8 +624,8 @@ class TestProjectMemoryRailCacheInvalidation:
rail.init(agent)
# First load
- await rail.before_model_call(ctx=MagicMock())
- body1 = agent.system_prompt_builder.added_sections[-1].content["en"]
+ await rail.before_model_call(ctx=_make_ctx(agent))
+ body1 = await _project_memory_body(agent)
assert "ORIGINAL-CONTENT" in body1
# Simulate write tool call — should invalidate cache
@@ -624,8 +638,8 @@ class TestProjectMemoryRailCacheInvalidation:
_touch(root, "JIUWENSWARM.md", "UPDATED-CONTENT")
# Reload after invalidation
- await rail.before_model_call(ctx=MagicMock())
- body2 = agent.system_prompt_builder.added_sections[-1].content["en"]
+ await rail.before_model_call(ctx=_make_ctx(agent))
+ body2 = await _project_memory_body(agent)
assert "UPDATED-CONTENT" in body2
assert "ORIGINAL-CONTENT" not in body2
@@ -641,8 +655,8 @@ class TestProjectMemoryRailCacheInvalidation:
rail.init(agent)
# First load
- await rail.before_model_call(ctx=MagicMock())
- body1 = agent.system_prompt_builder.added_sections[-1].content["en"]
+ await rail.before_model_call(ctx=_make_ctx(agent))
+ body1 = await _project_memory_body(agent)
assert "STABLE-CONTENT" in body1
# Simulate read tool call — should NOT invalidate
@@ -685,21 +699,18 @@ class TestProjectMemoryRailLanguagePropagation:
rail = ProjectMemoryRail(workspace=str(root), language="cn")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- section = agent.system_prompt_builder.added_sections[-1]
- assert "项目记忆" in section.content["cn"]
- assert "Project Memory" in section.content["en"]
+ cn_body = await _project_memory_body(agent)
+ assert "项目记忆" in cn_body
# Switch to English
rail.set_language("en")
assert rail.get_language() == "en"
- # Reload — section content keys stay bilingual (both cn+en always populated)
- await rail.before_model_call(ctx=MagicMock())
- section2 = agent.system_prompt_builder.added_sections[-1]
- assert "项目记忆" in section2.content["cn"]
- assert "Project Memory" in section2.content["en"]
+ await rail.before_model_call(ctx=_make_ctx(agent))
+ en_body = await _project_memory_body(agent)
+ assert "Project Memory" in en_body
@pytest.mark.asyncio
async def test_get_language_returns_initial_language(self):
@@ -720,4 +731,4 @@ class TestProjectMemoryRailLanguagePropagation:
async def test_set_language_ignores_empty(self):
rail = ProjectMemoryRail(workspace="/tmp", language="cn")
rail.set_language("") # empty → no-op
- assert rail.get_language() == "cn"
\ No newline at end of file
+ assert rail.get_language() == "cn"
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 00d4407a17..a13a063c0c 100644
--- a/tests/unit_tests/agentserver/rails/test_project_memory_rail.py
+++ b/tests/unit_tests/agentserver/rails/test_project_memory_rail.py
@@ -11,6 +11,8 @@ 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 (
@@ -58,9 +60,34 @@ 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
+def _make_ctx(agent: MagicMock, session_id: str = "sess1") -> SimpleNamespace:
+ return SimpleNamespace(
+ agent=agent,
+ session=SimpleNamespace(session_id=session_id),
+ inputs=SimpleNamespace(),
+ extra={},
+ )
+
+
+async def _project_memory_attachment(agent: MagicMock, session_id: str = "sess1"):
+ items = await agent.prompt_attachment_manager.collect_for_turn(session_id, "turn1")
+ 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_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
+
+
@pytest.mark.asyncio
async def test_loads_jiuwenswarm_md_from_root():
with tempfile.TemporaryDirectory() as td:
@@ -71,14 +98,13 @@ async def test_loads_jiuwenswarm_md_from_root():
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- sections = agent.system_prompt_builder.added_sections
- assert sections
- section = sections[-1]
- assert section.name == SECTION_NAME
- assert "PROJECT RULE 1" in section.content["en"]
- assert "PROJECT RULE 1" in section.content["cn"]
+ section = await _project_memory_attachment(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()
@pytest.mark.asyncio
@@ -91,11 +117,11 @@ async def test_section_is_bilingual_with_localized_headers():
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- section = agent.system_prompt_builder.added_sections[-1]
- assert "Project Memory" in section.content["en"]
- assert "项目记忆" in section.content["cn"]
+ section = await _project_memory_attachment(agent)
+ assert section is not None
+ assert "Project Memory" in section.content
@pytest.mark.asyncio
@@ -109,9 +135,9 @@ async def test_merges_nested_project_memory_files():
rail = ProjectMemoryRail(workspace=str(root), language="cn")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["cn"]
+ body = await _project_memory_body(agent, "cn")
assert "JIUWEN-CONTENT" in body
assert "NESTED-JIUWEN-CONTENT" in body
@@ -127,9 +153,9 @@ async def test_local_takes_highest_priority_position():
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent, "en")
assert body.index("PROJECT-LINE") < body.index("LOCAL-LINE")
@@ -142,13 +168,9 @@ async def test_empty_directory_no_section():
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- project_sections = [
- s for s in agent.system_prompt_builder.added_sections
- if s.name == SECTION_NAME
- ]
- assert project_sections == []
+ assert await _project_memory_attachment(agent) is None
@pytest.mark.asyncio
@@ -163,9 +185,9 @@ async def test_walk_up_from_subdir():
rail = ProjectMemoryRail(workspace=str(sub), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent, "en")
assert "ROOT-RULE" in body
@@ -179,13 +201,13 @@ async def test_refreshes_after_file_change():
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
- body1 = agent.system_prompt_builder.added_sections[-1].content["en"]
+ await rail.before_model_call(ctx=_make_ctx(agent))
+ body1 = await _project_memory_body(agent, "en")
assert "VERSION-1" in body1
_touch(root, "JIUWENSWARM.md", "VERSION-2")
- await rail.before_model_call(ctx=MagicMock())
- body2 = agent.system_prompt_builder.added_sections[-1].content["en"]
+ await rail.before_model_call(ctx=_make_ctx(agent))
+ body2 = await _project_memory_body(agent, "en")
assert "VERSION-2" in body2
assert "VERSION-1" not in body2
@@ -201,13 +223,9 @@ async def test_ignores_legacy_runtime_files():
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- sections = [
- s for s in agent.system_prompt_builder.added_sections
- if s.name == SECTION_NAME
- ]
- assert sections == []
+ assert await _project_memory_attachment(agent) is None
@pytest.mark.asyncio
@@ -221,9 +239,9 @@ async def test_reads_rules_glob_dir():
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent, "en")
assert "STYLE-RULE" in body
assert "TEST-RULE" in body
@@ -243,9 +261,9 @@ async def test_supports_include_directives():
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent, "en")
assert "ROOT-LINE" in body
assert "TAIL-LINE" in body
assert "SHARED-RULE" in body
@@ -268,9 +286,9 @@ async def test_conditional_rule_matches_workspace_subdir():
rail = ProjectMemoryRail(workspace=str(subdir), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent, "en")
assert "SCOPED-RULE" in body
@@ -290,9 +308,9 @@ async def test_conditional_rule_matches_inline_paths_list():
rail = ProjectMemoryRail(workspace=str(subdir), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent, "en")
assert "INLINE-SCOPED-RULE" in body
@@ -312,13 +330,9 @@ async def test_conditional_rule_skips_nonmatching_workspace():
rail = ProjectMemoryRail(workspace=str(docs), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- sections = [
- s for s in agent.system_prompt_builder.added_sections
- if s.name == SECTION_NAME
- ]
- assert sections == []
+ assert await _project_memory_attachment(agent) is None
@pytest.mark.asyncio
@@ -335,9 +349,9 @@ async def test_frontmatter_stripped():
rail = ProjectMemoryRail(workspace=str(root / "src"), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent, "en")
assert "BODY-ONLY" in body
assert "paths:" not in body
assert "version:" not in body
@@ -353,13 +367,9 @@ async def test_frontmatter_at_end_of_file_stripped():
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- sections = [
- s for s in agent.system_prompt_builder.added_sections
- if s.name == SECTION_NAME
- ]
- assert sections == []
+ assert await _project_memory_attachment(agent) is None
@pytest.mark.asyncio
@@ -372,23 +382,20 @@ async def test_uninit_clears_section():
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
- assert agent.system_prompt_builder.added_sections
+ await rail.before_model_call(ctx=_make_ctx(agent))
+ assert await _project_memory_attachment(agent) is not None
rail.uninit(agent)
- assert [
- s for s in agent.system_prompt_builder.added_sections
- if s.name == SECTION_NAME
- ] == []
+ assert agent.system_prompt_builder.remove_section.call_count == 0
@pytest.mark.asyncio
async def test_no_builder_is_safe():
rail = ProjectMemoryRail(workspace="/tmp", language="en")
- agent = MagicMock()
+ agent = SimpleNamespace()
agent.system_prompt_builder = None
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
@pytest.mark.asyncio
@@ -402,7 +409,7 @@ async def test_set_language_switches_active_language():
rail.set_language("en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
assert rail.get_language() == "en"
@@ -432,9 +439,9 @@ async def test_loads_user_and_managed_rules(monkeypatch):
rail = ProjectMemoryRail(workspace=str(root), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent, "en")
assert "USER-MEMORY" in body
assert "USER-RULE" in body
assert "MANAGED-MEMORY" in body
@@ -456,9 +463,9 @@ async def test_additional_directories_load_project_memory():
)
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent, "en")
assert "EXTRA-PROJECT-RULE" in body
@@ -483,9 +490,9 @@ async def test_additional_directories_relative_to_workspace():
)
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent, "en")
assert "RELATIVE-EXTRA-RULE" in body
@@ -501,14 +508,11 @@ async def test_b1_parent_set_workspace_does_not_break_path_resolution():
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- sections = [
- s for s in agent.system_prompt_builder.added_sections
- if s.name == SECTION_NAME
- ]
- assert sections
- assert "STILL-WORKING" in sections[-1].content["en"]
+ section = await _project_memory_attachment(agent)
+ assert section is not None
+ assert "STILL-WORKING" in section.content
@pytest.mark.asyncio
@@ -523,10 +527,11 @@ async def test_b1_no_workspace_falls_back_to_constructor_path():
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- section = agent.system_prompt_builder.added_sections[-1]
- assert "FROM-CTOR-PATH" in section.content["en"]
+ section = await _project_memory_attachment(agent)
+ assert section is not None
+ assert "FROM-CTOR-PATH" in section.content
@pytest.mark.asyncio
@@ -553,9 +558,9 @@ async def test_nested_worktree_skips_canonical_project_but_keeps_local(monkeypat
rail = ProjectMemoryRail(workspace=str(worktree), language="en")
agent = _make_agent_with_builder()
rail.init(agent)
- await rail.before_model_call(ctx=MagicMock())
+ await rail.before_model_call(ctx=_make_ctx(agent))
- body = agent.system_prompt_builder.added_sections[-1].content["en"]
+ body = await _project_memory_body(agent, "en")
assert "WORKTREE-PROJECT" in body
assert "CANONICAL-LOCAL" in body
assert "CANONICAL-PROJECT" not in body
diff --git a/tests/unit_tests/agentserver/test_prompt_attachment_loader.py b/tests/unit_tests/agentserver/test_prompt_attachment_loader.py
new file mode 100644
index 0000000000..6c5edfafef
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_prompt_attachment_loader.py
@@ -0,0 +1,516 @@
+from __future__ import annotations
+
+import os
+from types import SimpleNamespace
+
+import pytest
+
+from openjiuwen.core.foundation.llm import SystemMessage, UserMessage
+from openjiuwen.harness.prompts.prompt_attachment_manager import (
+ PromptAttachment,
+ PromptAttachmentKind,
+ PromptAttachmentManager,
+ PromptAttachmentScope,
+ PromptAttachmentUpdate,
+)
+
+from jiuwenswarm.server.runtime.prompt_attachment_loader import (
+ SESSION_SOURCE,
+ TURN_SOURCE,
+ PromptAttachmentLoader,
+ sanitize_session_id,
+)
+import jiuwenswarm.server.runtime.prompt_attachment_loader as prompt_attachment_loader_module
+
+
+class FakeDeepAgent:
+ def __init__(self) -> None:
+ self.prompt_attachment_manager = PromptAttachmentManager()
+
+
+def test_sanitize_session_id_is_path_safe():
+ assert sanitize_session_id("") == "default"
+ assert sanitize_session_id("default") == "default"
+ assert "/" not in sanitize_session_id("../unsafe/session")
+ assert "\\" not in sanitize_session_id("a\\b")
+ assert sanitize_session_id("..") != ".."
+
+
+def test_loader_ensure_layout_and_loads_stable_order_kind_and_ids(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ loader.ensure_layout()
+
+ session_dir = root / "sess1" / "session"
+ session_dir.mkdir(parents=True)
+ (session_dir / "z_note.txt").write_text("z", encoding="utf-8")
+ (session_dir / "runtime.md").write_text("runtime", encoding="utf-8")
+ (session_dir / "diagnostics.md").write_text("diag", encoding="utf-8")
+ (session_dir / ".hidden.md").write_text("hidden", encoding="utf-8")
+ (session_dir / "image.png").write_text("ignored", encoding="utf-8")
+
+ items = loader.load_session_attachments("sess1")
+
+ assert (root / "README.md").exists()
+ readme = (root / "README.md").read_text(encoding="utf-8")
+ assert "not user-uploaded attachments" in readme
+ assert all(ord(char) < 128 for char in readme)
+ assert [item.id for item in items] == [
+ "session.sess1.diagnostics",
+ "session.sess1.runtime",
+ "session.sess1.z_note",
+ ]
+ assert [item.kind.value if hasattr(item.kind, "value") else item.kind for item in items] == [
+ "diagnostic",
+ "runtime",
+ "text",
+ ]
+
+
+def test_loader_skips_empty_files_and_truncates_large_files(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root, max_file_chars=5)
+ session_dir = root / "sess1" / "session"
+ session_dir.mkdir(parents=True)
+ (session_dir / "empty.md").write_text(" \n", encoding="utf-8")
+ (session_dir / "runtime.md").write_text("x" * 20, encoding="utf-8")
+
+ items = loader.load_session_attachments("sess1")
+
+ assert [item.id for item in items] == ["session.sess1.runtime"]
+ assert items[0].content.startswith("xxxxx")
+ assert "truncated by jiuwenswarm loader" in items[0].content
+
+
+def test_user_friendly_for_context_add_markdown_hides_session_and_turn(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ ctx = SimpleNamespace(session_id="sess1", invoke_turn_id="req1")
+
+ item = loader.for_context(ctx).add_markdown(
+ name="hint.md",
+ scope="turn",
+ content="turn hint",
+ priority=42,
+ )
+ items = loader.load_turn_attachments("sess1", "req1")
+
+ assert item.id == "turn.sess1.req1.hint"
+ assert item.priority == 42
+ assert item.kind == PromptAttachmentKind.TEXT
+ assert item.source == TURN_SOURCE
+ assert item.metadata["origin_source"] == "jiuwenswarm.prompt_attachment.user"
+ assert [loaded.id for loaded in items] == ["turn.sess1.req1.hint"]
+ assert [loaded.content for loaded in items] == ["turn hint"]
+
+
+def test_context_store_update_get_delete_and_list_use_bound_ids(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ store = loader.for_context(SimpleNamespace(session_id="sess1", invoke_turn_id="req1"))
+ created = store.add_markdown(name="hint.md", content="turn hint")
+
+ updated = store.update_markdown(
+ created.id,
+ scope=PromptAttachmentScope.TURN,
+ content="turn hint v2",
+ )
+ listed = store.list(scope=PromptAttachmentScope.TURN)
+
+ assert updated.content == "turn hint v2"
+ assert store.get(created.id, scope=PromptAttachmentScope.TURN).content == "turn hint v2"
+ assert [item.id for item in listed] == ["turn.sess1.req1.hint"]
+ assert store.delete(created.id, scope=PromptAttachmentScope.TURN) is True
+ assert store.get(created.id, scope=PromptAttachmentScope.TURN) is None
+
+
+def test_file_store_add_markdown_validates_paths_and_turn_context(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+
+ with pytest.raises(ValueError):
+ loader.file_store.add_markdown(
+ session_id="sess1",
+ scope=PromptAttachmentScope.TURN,
+ name="note.md",
+ content="missing turn",
+ )
+ with pytest.raises(ValueError):
+ loader.file_store.add_markdown(session_id="sess1", name="../unsafe.md", content="unsafe")
+ with pytest.raises(ValueError):
+ loader.file_store.add_markdown(session_id="sess1", name=".hidden.md", content="hidden")
+
+
+def test_update_markdown_preserves_frontmatter_and_merges_metadata(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ session_store = loader.for_session("sess1")
+ created = session_store.add_session_markdown(
+ name="release.md",
+ content="old content",
+ priority=80,
+ source="external.user",
+ metadata={"owner": "qa"},
+ )
+
+ updated = session_store.update_markdown(
+ created.id,
+ content="new content",
+ metadata={"ticket": "123"},
+ )
+ loaded = loader.load_session_attachments("sess1")[0]
+ raw = (root / "sess1" / "session" / "release.md").read_text(encoding="utf-8")
+
+ assert updated.content == "new content"
+ assert loaded.priority == 80
+ assert loaded.source == SESSION_SOURCE
+ assert loaded.metadata["origin_source"] == "external.user"
+ assert loaded.metadata["owner"] == "qa"
+ assert loaded.metadata["ticket"] == 123
+ assert "priority: 80" in raw
+ assert "owner: qa" in raw
+ assert "ticket: 123" in raw
+
+
+def test_file_store_json_prompt_attachment_syncs_to_manager(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ created = loader.file_store.add(PromptAttachment(
+ id="external.release_notes",
+ scope=PromptAttachmentScope.SESSION,
+ kind=PromptAttachmentKind.TEXT,
+ content="json content",
+ priority=12,
+ source="external.user",
+ session_id="sess1",
+ metadata={"owner": "qa"},
+ content_kind="text/markdown",
+ ))
+
+ updated = loader.file_store.update(
+ "external.release_notes",
+ PromptAttachmentUpdate(content="json content v2", metadata={"ticket": "123"}),
+ )
+ items = loader.load_session_attachments("sess1")
+
+ assert created.id == "external.release_notes"
+ assert (root / "sess1" / "session" / "external.release_notes.json").exists()
+ assert updated.content == "json content v2"
+ assert updated.metadata["owner"] == "qa"
+ assert updated.metadata["ticket"] == "123"
+ assert [item.id for item in items] == ["external.release_notes"]
+ assert [item.content for item in items] == ["json content v2"]
+ assert [item.priority for item in items] == [12]
+ assert [item.source for item in items] == [SESSION_SOURCE]
+ assert [item.metadata["origin_source"] for item in items] == ["external.user"]
+ assert [item.metadata["owner"] for item in items] == ["qa"]
+ assert [item.metadata["ticket"] for item in items] == ["123"]
+
+
+def test_session_bound_crud_does_not_find_json_from_other_sessions(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ loader.file_store.add(PromptAttachment(
+ id="external.secret",
+ scope=PromptAttachmentScope.SESSION,
+ kind=PromptAttachmentKind.TEXT,
+ content="sess b secret",
+ session_id="sessB",
+ ))
+
+ sess_a = loader.for_session("sessA")
+
+ assert sess_a.get("external.secret") is None
+ assert sess_a.delete("external.secret") is False
+ with pytest.raises(FileNotFoundError):
+ sess_a.update_markdown("external.secret", content="overwrite")
+ assert loader.for_session("sessB").get("external.secret").content == "sess b secret"
+
+
+def test_update_markdown_does_not_rewrite_json_attachment(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ loader.file_store.add(PromptAttachment(
+ id="external.release_notes",
+ scope=PromptAttachmentScope.SESSION,
+ kind=PromptAttachmentKind.TEXT,
+ content="json content",
+ session_id="sess1",
+ ))
+ json_path = root / "sess1" / "session" / "external.release_notes.json"
+ before = json_path.read_text(encoding="utf-8")
+
+ with pytest.raises(FileNotFoundError):
+ loader.for_session("sess1").update_markdown("external.release_notes", content="markdown content")
+
+ assert json_path.read_text(encoding="utf-8") == before
+ assert loader.for_session("sess1").get("external.release_notes").content == "json content"
+
+
+def test_file_store_list_without_turn_id_includes_session_and_turn_items(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ store = loader.for_session("sess1", invoke_turn_id="req1")
+
+ store.add_session_markdown(name="session.md", content="session content")
+ store.add_current_turn_markdown(name="turn.md", content="turn content")
+ items = loader.file_store.list(session_id="sess1")
+
+ assert [item.id for item in items] == ["session.sess1.session", "turn.sess1.req1.turn"]
+ assert [item.content for item in items] == ["session content", "turn content"]
+
+
+def test_file_store_auto_name_uses_unique_time_ns_and_thread_id(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ store = loader.for_session("sess1")
+
+ first = store.add_session_markdown(content="one")
+ second = store.add_session_markdown(content="two")
+
+ assert first.id != second.id
+ assert [item.content for item in store.list()] == ["one", "two"]
+
+
+def test_loader_skips_symlinked_prompt_attachment_paths(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ session_dir = root / "sess1" / "session"
+ session_dir.mkdir(parents=True)
+ (session_dir / "runtime.md").write_text("inside", encoding="utf-8")
+ outside_dir = tmp_path / "outside"
+ outside_dir.mkdir()
+ (outside_dir / "secret.md").write_text("outside secret", encoding="utf-8")
+ link_dir = session_dir / "linked"
+ try:
+ os.symlink(outside_dir, link_dir, target_is_directory=True)
+ except (OSError, NotImplementedError) as exc:
+ pytest.skip(f"symlink creation is unavailable: {exc}")
+
+ items = loader.load_session_attachments("sess1")
+
+ assert [item.content for item in items] == ["inside"]
+
+
+def test_loader_skips_reparse_marked_prompt_attachment_paths(tmp_path, monkeypatch):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ session_dir = root / "sess1" / "session"
+ linked_dir = session_dir / "linked"
+ linked_dir.mkdir(parents=True)
+ (linked_dir / "secret.md").write_text("outside secret", encoding="utf-8")
+ (session_dir / "runtime.md").write_text("inside", encoding="utf-8")
+
+ def fake_is_reparse_path(path):
+ return path == linked_dir
+
+ monkeypatch.setattr(prompt_attachment_loader_module, "_is_reparse_path", fake_is_reparse_path)
+
+ items = loader.load_session_attachments("sess1")
+
+ assert [item.content for item in items] == ["inside"]
+
+
+async def test_sync_to_agent_removes_deleted_user_source_turn_files(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ agent = FakeDeepAgent()
+ store = loader.for_session("sess1", invoke_turn_id="req1")
+
+ created = store.add_current_turn_markdown(name="hint.md", content="turn hint")
+ assert created.source == TURN_SOURCE
+ assert created.metadata["origin_source"] == "jiuwenswarm.prompt_attachment.user"
+
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req1")
+ loaded = await agent.prompt_attachment_manager.list_by_filter(
+ session_id="sess1",
+ invoke_turn_id="req1",
+ scope=PromptAttachmentScope.TURN,
+ )
+ assert [item.id for item in loaded] == ["turn.sess1.req1.hint"]
+ assert [item.source for item in loaded] == [TURN_SOURCE]
+
+ assert store.delete(created.id, scope=PromptAttachmentScope.TURN) is True
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req1")
+
+ assert await agent.prompt_attachment_manager.list_by_filter(
+ session_id="sess1",
+ invoke_turn_id="req1",
+ scope=PromptAttachmentScope.TURN,
+ ) == []
+
+
+async def test_sync_to_agent_hot_reloads_session_modify_and_delete(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ agent = FakeDeepAgent()
+ session_dir = root / "sess1" / "session"
+ session_dir.mkdir(parents=True)
+ runtime_path = session_dir / "runtime.md"
+
+ runtime_path.write_text("v1", encoding="utf-8")
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req1")
+ items = await agent.prompt_attachment_manager.collect_for_turn("sess1", "req1")
+ assert [item.content for item in items] == ["v1"]
+
+ runtime_path.write_text("v2", encoding="utf-8")
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req2")
+ items = await agent.prompt_attachment_manager.collect_for_turn("sess1", "req2")
+ assert [item.content for item in items] == ["v2"]
+
+ runtime_path.unlink()
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req3")
+ items = await agent.prompt_attachment_manager.collect_for_turn("sess1", "req3")
+ assert items == []
+
+
+async def test_sync_to_agent_keeps_turn_attachments_isolated_by_request(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ agent = FakeDeepAgent()
+ turn_dir = root / "sess1" / "turn"
+ req1_dir = turn_dir / "req1"
+ req2_dir = turn_dir / "req2"
+ req1_dir.mkdir(parents=True)
+ req2_dir.mkdir(parents=True)
+
+ (req1_dir / "request_context.md").write_text("turn 1 only", encoding="utf-8")
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req1")
+ req1_items = await agent.prompt_attachment_manager.collect_for_turn("sess1", "req1")
+ assert [item.content for item in req1_items] == ["turn 1 only"]
+
+ (req2_dir / "request_context.md").write_text("turn 2 only", encoding="utf-8")
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req2")
+ req2_items = await agent.prompt_attachment_manager.collect_for_turn("sess1", "req2")
+ assert [item.content for item in req2_items] == ["turn 2 only"]
+ stale_turn_items = await agent.prompt_attachment_manager.list_by_filter(
+ source=TURN_SOURCE,
+ session_id="sess1",
+ scope=PromptAttachmentScope.TURN,
+ )
+ assert [item.invoke_turn_id for item in stale_turn_items] == ["req1", "req2"]
+ req1_contents = [
+ item.content
+ for item in await agent.prompt_attachment_manager.collect_for_turn("sess1", "req1")
+ ]
+ assert req1_contents == ["turn 1 only"]
+
+ (turn_dir / "req3").mkdir()
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req3")
+ req3_items = await agent.prompt_attachment_manager.collect_for_turn("sess1", "req3")
+ assert req3_items == []
+
+ await loader.clear_turn_from_agent(agent, session_id="sess1", invoke_turn_id="req1")
+ await loader.clear_turn_from_agent(agent, session_id="sess1", invoke_turn_id="req2")
+ assert await agent.prompt_attachment_manager.list_by_filter(source=TURN_SOURCE, session_id="sess1") == []
+
+
+async def test_sync_to_agent_reads_isolated_turn_directory_only(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ agent = FakeDeepAgent()
+ turn_root = root / "sess1" / "turn"
+ req1_dir = turn_root / "req1"
+ req2_dir = turn_root / "req2"
+ req1_dir.mkdir(parents=True)
+ req2_dir.mkdir(parents=True)
+ (req1_dir / "request_context.md").write_text("req1 only", encoding="utf-8")
+ (req2_dir / "request_context.md").write_text("req2 only", encoding="utf-8")
+
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req1")
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req2")
+
+ req1_items = await agent.prompt_attachment_manager.collect_for_turn("sess1", "req1")
+ req2_items = await agent.prompt_attachment_manager.collect_for_turn("sess1", "req2")
+ assert [item.content for item in req1_items] == ["req1 only"]
+ assert [item.content for item in req2_items] == ["req2 only"]
+ assert [item.id for item in req1_items] == ["turn.sess1.req1.request_context"]
+ assert [item.id for item in req2_items] == ["turn.sess1.req2.request_context"]
+
+
+async def test_file_loaded_attachments_render_inject_and_turn_cleanup(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ agent = FakeDeepAgent()
+
+ session_dir = root / "sess1" / "session"
+ turn_dir = root / "sess1" / "turn" / "req1"
+ session_dir.mkdir(parents=True)
+ turn_dir.mkdir(parents=True)
+ (session_dir / "runtime.md").write_text("SESSION_FILE_MARKER", encoding="utf-8")
+ (turn_dir / "request_context.md").write_text("TURN_FILE_MARKER", encoding="utf-8")
+
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req1")
+ manager = agent.prompt_attachment_manager
+ rendered = manager.render(await manager.collect_for_turn("sess1", "req1"))
+ messages = [
+ SystemMessage(content="STATIC_SYSTEM_PROMPT"),
+ UserMessage(content="original query"),
+ ]
+
+ injected = manager.inject_messages(messages, rendered)
+
+ assert messages[-1].content == "original query"
+ assert injected[0].content == "STATIC_SYSTEM_PROMPT"
+ assert "SESSION_FILE_MARKER" not in injected[0].content
+ assert "TURN_FILE_MARKER" not in injected[0].content
+ assert "original query" in injected[-1].content
+ assert "<system-reminder>" in injected[-1].content
+ assert "SESSION_FILE_MARKER" in injected[-1].content
+ assert "TURN_FILE_MARKER" in injected[-1].content
+
+ await loader.clear_turn_from_agent(agent, session_id="sess1", invoke_turn_id="req1")
+ after_clear = await manager.collect_for_turn("sess1", "req1")
+ assert [item.content for item in after_clear] == ["SESSION_FILE_MARKER"]
+
+
+async def test_flat_turn_files_are_ignored(tmp_path):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ agent = FakeDeepAgent()
+ turn_root = root / "sess1" / "turn"
+ turn_root.mkdir(parents=True)
+ (turn_root / "request_context.md").write_text("legacy flat", encoding="utf-8")
+
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req1")
+
+ req1_items = await agent.prompt_attachment_manager.collect_for_turn("sess1", "req1")
+ assert req1_items == []
+
+
+async def test_sync_to_agent_read_failure_does_not_block_or_keep_old_turn(tmp_path, monkeypatch):
+ root = tmp_path / "prompt_attachment"
+ loader = PromptAttachmentLoader(root)
+ agent = FakeDeepAgent()
+ turn_dir = root / "sess1" / "turn" / "req1"
+ turn_dir.mkdir(parents=True)
+ (turn_dir / "request_context.md").write_text("turn 1", encoding="utf-8")
+
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req1")
+ assert await agent.prompt_attachment_manager.list_by_filter(source=TURN_SOURCE, session_id="sess1")
+
+ req2_dir = root / "sess1" / "turn" / "req2"
+ req2_dir.mkdir(parents=True)
+ (req2_dir / "request_context.md").write_text("turn 2", encoding="utf-8")
+
+ def fail_read(*args, **kwargs):
+ raise OSError("boom")
+
+ monkeypatch.setattr(loader, "_read_text_file", fail_read)
+ await loader.sync_to_agent(agent, session_id="sess1", invoke_turn_id="req2")
+
+ assert await agent.prompt_attachment_manager.collect_for_turn("sess1", "req2") == []
+ req1_contents = [
+ item.content
+ for item in await agent.prompt_attachment_manager.collect_for_turn("sess1", "req1")
+ ]
+ assert req1_contents == ["turn 1"]
+ session_items = await agent.prompt_attachment_manager.list_by_filter(source=SESSION_SOURCE, session_id="sess1")
+ assert session_items == []
diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
index 3319cfa316..d60af53c64 100644
--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py
+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
@@ -5,11 +5,17 @@ import pytest
from openjiuwen.core.foundation.llm import Model
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.harness.prompts.prompt_attachment_manager import (
+ PromptAttachment,
+ PromptAttachmentKind,
+ PromptAttachmentManager,
+ PromptAttachmentScope,
+)
from openjiuwen.harness.prompts import PromptSection, SystemPromptBuilder
from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenClawDeepAdapter
from jiuwenswarm.agents.harness.common.prompt.prompt_builder import build_agent_identity_prompt
-from jiuwenswarm.agents.harness.common.rails import runtime_prompt_rail as runtime_prompt_rail_module
+from jiuwenswarm.agents.harness.common.rails import runtime_prompt_rail as _runtime_mod
from jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import RuntimePromptRail
@@ -26,6 +32,17 @@ class _TestableJiuWenClawDeepAdapter(JiuWenClawDeepAdapter):
return self._build_configured_subagents(model, config, config_base)
+class _FakeSession:
+ def get_session_id(self) -> str:
+ return "sess1"
+
+
+class _FakeAgent:
+ def __init__(self, builder: SystemPromptBuilder) -> None:
+ self.system_prompt_builder = builder
+ self.prompt_attachment_manager = PromptAttachmentManager()
+
+
def test_build_agent_identity_prompt_contains_identity_section_only():
prompt = build_agent_identity_prompt(language="zh")
@@ -40,13 +57,19 @@ async def test_runtime_time_section_participates_in_priority_order():
builder.add_section(PromptSection(name="tools", content={"cn": "# 可用工具"}, priority=30))
builder.add_section(PromptSection(name="workspace", content={"cn": "# 工作空间"}, priority=70))
+ agent = _FakeAgent(builder)
runtime_rail = RuntimePromptRail(
language="cn",
channel="web"
)
- runtime_rail.init(SimpleNamespace(system_prompt_builder=builder))
+ runtime_rail.init(agent)
- ctx = AgentCallbackContext(agent=None, inputs=None, session=None)
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=None,
+ session=_FakeSession(),
+ extra={"_invoke_turn_id": "turn1"},
+ )
await runtime_rail.before_model_call(ctx)
prompt = builder.build()
@@ -55,16 +78,137 @@ async def test_runtime_time_section_participates_in_priority_order():
"# 可用工具",
"# 工作空间",
"# 时间说明",
- "# 运行时状态",
]
positions = [prompt.index(marker) for marker in ordered_markers]
assert positions == sorted(positions)
- assert "当前模型" in prompt
+ assert "当前模型" not in prompt
+
+
+async def test_runtime_dynamic_sections_go_to_prompt_attachment_when_manager_available(tmp_path, monkeypatch):
+ monkeypatch.setattr(_runtime_mod, "get_config_dir", lambda: tmp_path)
+ builder = SystemPromptBuilder(language="en")
+ agent = _FakeAgent(builder)
+ runtime_rail = RuntimePromptRail(language="en", channel="web")
+ runtime_rail.init(agent)
+ runtime_rail.set_model_name("model-x")
+ runtime_rail.set_mode("agent.plan")
+
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=None,
+ session=_FakeSession(),
+ extra={"_invoke_turn_id": "turn1"},
+ )
+ await runtime_rail.before_model_call(ctx)
+
+ 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 "# Environment" in prompt
+
+ items = await agent.prompt_attachment_manager.collect_for_turn("sess1", "turn1")
+ assert [item.id for item in items] == [
+ "turn.sess1.turn1.language_output",
+ "turn.sess1.turn1.runtime",
+ "turn.sess1.turn1.browser_tool_policy",
+ ]
+ 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
+
+
+async def test_runtime_git_status_attachment_clears_when_git_context_disappears(tmp_path, monkeypatch):
+ monkeypatch.setattr(_runtime_mod, "get_config_dir", lambda: tmp_path)
+ runtime_state = tmp_path / "runtime_state.yaml"
+ runtime_state.write_text(
+ "git_branch: feature/test\n"
+ "git_status: M file.py\n"
+ "git_recent_commits: abc init\n",
+ encoding="utf-8",
+ )
+ builder = SystemPromptBuilder(language="en")
+ agent = _FakeAgent(builder)
+ runtime_rail = RuntimePromptRail(language="en", channel="web")
+ runtime_rail.init(agent)
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=None,
+ session=_FakeSession(),
+ extra={"_invoke_turn_id": "turn1"},
+ )
+
+ await runtime_rail.before_model_call(ctx)
+ session_items = await agent.prompt_attachment_manager.list_by_filter(session_id="sess1", scope="session")
+ assert [item.id for item in session_items if item.id.endswith(".git_status")] == ["session.sess1.git_status"]
+
+ runtime_state.write_text("git_branch: ''\n", encoding="utf-8")
+ await runtime_rail.before_model_call(ctx)
+ session_items = await agent.prompt_attachment_manager.list_by_filter(session_id="sess1", scope="session")
+ assert [item.id for item in session_items if item.id.endswith(".git_status")] == []
+
+
+async def test_deep_adapter_clears_all_current_turn_prompt_attachments():
+ builder = SystemPromptBuilder(language="en")
+ agent = _FakeAgent(builder)
+ adapter = JiuWenClawDeepAdapter.__new__(JiuWenClawDeepAdapter)
+ adapter._instance = agent
+ adapter._prompt_attachment_loader = None
+
+ await agent.prompt_attachment_manager.add(PromptAttachment(
+ id="turn.sess1.turn1.runtime",
+ scope=PromptAttachmentScope.TURN,
+ kind=PromptAttachmentKind.RUNTIME,
+ content="runtime",
+ source="jiuwenswarm.runtime_prompt.runtime",
+ session_id="sess1",
+ invoke_turn_id="turn1",
+ ))
+ await agent.prompt_attachment_manager.add(PromptAttachment(
+ id="turn.sess1.turn1.avatar",
+ scope=PromptAttachmentScope.TURN,
+ kind=PromptAttachmentKind.RUNTIME,
+ content="avatar",
+ source="jiuwenswarm.avatar.avatar_identity",
+ session_id="sess1",
+ invoke_turn_id="turn1",
+ ))
+ await agent.prompt_attachment_manager.add(PromptAttachment(
+ id="turn.sess1.turn2.runtime",
+ scope=PromptAttachmentScope.TURN,
+ kind=PromptAttachmentKind.RUNTIME,
+ content="other turn",
+ source="jiuwenswarm.runtime_prompt.runtime",
+ session_id="sess1",
+ invoke_turn_id="turn2",
+ ))
+ await agent.prompt_attachment_manager.add(PromptAttachment(
+ id="session.sess1.project_memory",
+ scope=PromptAttachmentScope.SESSION,
+ kind=PromptAttachmentKind.MEMORY,
+ content="session",
+ source="jiuwenswarm.project_memory",
+ session_id="sess1",
+ ))
+
+ await adapter._clear_prompt_attachments_for_request("sess1", "turn1")
+
+ remaining = await agent.prompt_attachment_manager.list_by_filter(session_id="sess1")
+ assert [item.id for item in remaining] == [
+ "session.sess1.project_memory",
+ "turn.sess1.turn2.runtime",
+ ]
@pytest.mark.asyncio
async def test_runtime_prompt_uses_runtime_cwd_over_stale_trusted_dir(tmp_path):
builder = SystemPromptBuilder(language="en")
+ agent = _FakeAgent(builder)
stale_dir = tmp_path / "missing-worktree"
project_dir = tmp_path / "project"
current_dir = project_dir / "current"
@@ -73,18 +217,27 @@ async def test_runtime_prompt_uses_runtime_cwd_over_stale_trusted_dir(tmp_path):
extra_dir.mkdir()
runtime_rail = RuntimePromptRail(language="en", channel="tui")
- runtime_rail.init(SimpleNamespace(system_prompt_builder=builder))
+ runtime_rail.init(agent)
runtime_rail.set_trusted_dirs([str(stale_dir), str(current_dir), str(extra_dir)])
runtime_rail.set_runtime_paths(cwd=str(current_dir), project_dir=str(project_dir))
- ctx = AgentCallbackContext(agent=None, inputs=None, session=None)
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=None,
+ session=_FakeSession(),
+ extra={"_invoke_turn_id": "turn1"},
+ )
await runtime_rail.before_model_call(ctx)
prompt = builder.build()
- assert "Current project directory" in prompt
- assert str(current_dir) in prompt
- assert str(stale_dir) not in prompt
- assert str(extra_dir) in prompt
+ assert "Current project directory" not in prompt
+ rendered = agent.prompt_attachment_manager.render(
+ await agent.prompt_attachment_manager.collect_for_turn("sess1", "turn1")
+ )
+ assert "Current project directory" in rendered
+ assert str(current_dir) in rendered
+ assert str(stale_dir) not in rendered
+ assert str(extra_dir) in rendered
@pytest.mark.asyncio
@@ -98,19 +251,30 @@ async def test_runtime_prompt_language_output_prefers_rail_language_over_runtime
"model: test-model\nmode: team.plan\nlanguage: en\nchannel: tui\n",
encoding="utf-8",
)
- monkeypatch.setattr(runtime_prompt_rail_module, "get_config_dir", lambda: config_dir)
+ monkeypatch.setattr(_runtime_mod, "get_config_dir", lambda: config_dir)
builder = SystemPromptBuilder(language="cn")
+ agent = _FakeAgent(builder)
runtime_rail = RuntimePromptRail(language="cn", channel="tui")
- runtime_rail.init(SimpleNamespace(system_prompt_builder=builder))
+ runtime_rail.init(agent)
- ctx = AgentCallbackContext(agent=None, inputs=None, session=None)
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=None,
+ session=_FakeSession(),
+ extra={"_invoke_turn_id": "turn1"},
+ )
await runtime_rail.before_model_call(ctx)
prompt = builder.build()
- assert "Always respond in Chinese." in prompt
+ assert "Always respond in Chinese." not in prompt
+ rendered = agent.prompt_attachment_manager.render(
+ await agent.prompt_attachment_manager.collect_for_turn("sess1", "turn1")
+ )
+ assert "Always respond in Chinese." in rendered
+ assert "Always respond in English." not in rendered
assert "Always respond in English." not in prompt
- assert "当前语言:cn" in prompt
+ assert "当前语言:cn" in rendered
def test_resolve_skill_mode_accepts_all_and_auto_list():