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): align prompt attachment loader with session sections
MengHan182a61cc8f8371
diff --git a/jiuwenswarm/agents/harness/common/rails/avatar_rail.py b/jiuwenswarm/agents/harness/common/rails/avatar_rail.pyindex 2522314c91..eedb63fb2e 100644--- a/jiuwenswarm/agents/harness/common/rails/avatar_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/avatar_rail.py@@ -14,7 +14,6 @@ from openjiuwen.core.single_agent.rail.base import AgentCallbackContextfrom openjiuwen.harness.prompts import PromptSectionfrom openjiuwen.harness.prompts.prompt_attachment_manager import (PromptAttachmentKind,- PromptAttachmentScope,)from openjiuwen.harness.rails.base import DeepAgentRail@@ -195,16 +194,12 @@ class AvatarPromptRail(DeepAgentRail):logger.warning("[AvatarRail] skip avatar context: prompt attachment manager unavailable")returntry:- writer = self.attachment_manager.for_context(ctx)+ writer = self.attachment_manager.bind_context(ctx)for section in _AVATAR_SECTION_PRIORITIES:- await writer.clear_section(- section=section,- scope=PromptAttachmentScope.TURN,- )+ await writer.clear_section(section)for section in sections:- await writer.upsert_from_section(+ await writer.add_from_prompt_section(section=section,- scope=PromptAttachmentScope.TURN,kind=PromptAttachmentKind.RUNTIME,source=f"jiuwenswarm.avatar.{section.name}",language=language,diff --git a/jiuwenswarm/agents/harness/common/rails/project_memory_rail.py b/jiuwenswarm/agents/harness/common/rails/project_memory_rail.pyindex 68375f7950..e792cccd1b 100644--- a/jiuwenswarm/agents/harness/common/rails/project_memory_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/project_memory_rail.py@@ -20,7 +20,6 @@ from typing import TYPE_CHECKINGfrom openjiuwen.core.single_agent.rail.base import AgentCallbackContextfrom openjiuwen.harness.prompts.prompt_attachment_manager import (PromptAttachmentKind,- PromptAttachmentScope,)from openjiuwen.harness.rails.base import DeepAgentRail@@ -217,9 +216,8 @@ class ProjectMemoryRail(DeepAgentRail):logger.warning("[ProjectMemoryRail] skip project memory: prompt attachment manager unavailable")returntry:- await self.attachment_manager.for_context(ctx).upsert_from_section(- section=section,- scope=PromptAttachmentScope.SESSION,+ await self.attachment_manager.bind_context(ctx).add_from_prompt_section(+ prompt_section=section,kind=PromptAttachmentKind.MEMORY,source="jiuwenswarm.project_memory",priority=self.SECTION_PRIORITY,@@ -234,10 +232,7 @@ class ProjectMemoryRail(DeepAgentRail):if self.attachment_manager is None:returntry:- await self.attachment_manager.for_context(ctx).clear_section(- section=SECTION_NAME,- scope=PromptAttachmentScope.SESSION,- )+ await self.attachment_manager.bind_context(ctx).clear_section(SECTION_NAME)except ValueError as exc:logger.warning("[ProjectMemoryRail] skip clearing project memory prompt attachment: %s", exc)diff --git a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.pyindex ad28f19141..98a075934f 100644--- a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py@@ -18,7 +18,6 @@ from openjiuwen.core.single_agent.rail.base import AgentCallbackContextfrom openjiuwen.harness.prompts import PromptSectionfrom openjiuwen.harness.prompts.prompt_attachment_manager import (PromptAttachmentKind,- PromptAttachmentScope,)from openjiuwen.harness.rails.base import DeepAgentRailfrom jiuwenswarm.agents.harness.common.prompt.shell_environment import build_shell_environment_prompt@@ -200,7 +199,6 @@ class RuntimePromptRail(DeepAgentRail):ctx,section="runtime",content=runtime_content,- scope=PromptAttachmentScope.TURN,kind=PromptAttachmentKind.RUNTIME,source="jiuwenswarm.runtime_prompt.runtime",priority=95,@@ -220,7 +218,6 @@ class RuntimePromptRail(DeepAgentRail):ctx,section="language_output",content=language_output_content,- scope=PromptAttachmentScope.TURN,kind=PromptAttachmentKind.RUNTIME,source="jiuwenswarm.runtime_prompt.language_output",priority=93,@@ -325,7 +322,6 @@ class RuntimePromptRail(DeepAgentRail):ctx,section="git_status",content=git_content,- scope=PromptAttachmentScope.SESSION,kind=PromptAttachmentKind.WORKSPACE_DELTA,source="jiuwenswarm.runtime_prompt.git_status",priority=87,@@ -334,7 +330,6 @@ class RuntimePromptRail(DeepAgentRail):await self._clear_prompt_attachment(ctx,section="git_status",- scope=PromptAttachmentScope.SESSION,)self.system_prompt_builder.remove_section("browser_tool_policy")@@ -354,7 +349,6 @@ class RuntimePromptRail(DeepAgentRail):ctx,section="browser_tool_policy",content=browser_tool_policy,- scope=PromptAttachmentScope.TURN,kind=PromptAttachmentKind.RUNTIME,source="jiuwenswarm.runtime_prompt.browser_tool_policy",priority=98,@@ -363,7 +357,6 @@ class RuntimePromptRail(DeepAgentRail):await self._clear_prompt_attachment(ctx,section="browser_tool_policy",- scope=PromptAttachmentScope.TURN,)if self._channel == "tui":@@ -427,13 +420,15 @@ class RuntimePromptRail(DeepAgentRail):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")+ await self._clear_prompt_attachment(ctx, section="trusted_dirs")+ else:+ await self._clear_prompt_attachment(ctx, section="trusted_dirs")async def _upsert_prompt_attachment(self,@@ -441,7 +436,6 @@ class RuntimePromptRail(DeepAgentRail):*,section: str,content: str,- scope: PromptAttachmentScope,kind: PromptAttachmentKind,source: str,priority: int,@@ -453,11 +447,10 @@ class RuntimePromptRail(DeepAgentRail):)returntry:- writer = self.attachment_manager.for_context(ctx)- await writer.upsert_section(+ writer = self.attachment_manager.bind_context(ctx)+ await writer.add_section(section=section,content=content,- scope=scope,kind=kind,source=source,priority=priority,@@ -471,14 +464,10 @@ class RuntimePromptRail(DeepAgentRail):ctx: AgentCallbackContext,*,section: str,- scope: PromptAttachmentScope,) -> None:if self.attachment_manager is None:returntry:- await self.attachment_manager.for_context(ctx).clear_section(- section=section,- scope=scope,- )+ await self.attachment_manager.bind_context(ctx).clear_section(section)except ValueError as exc:logger.warning("[RuntimePromptRail] skip clearing prompt attachment section=%s: %s", section, exc)diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 227616bcd8..1038bd3604 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -51,7 +51,6 @@ from openjiuwen.harness import ()from openjiuwen.harness.factory import create_deep_agentfrom openjiuwen.harness.prompts import resolve_language-from openjiuwen.harness.prompts.prompt_attachment_manager import PromptAttachmentScopefrom openjiuwen.harness.rails import (SkillUseRail,TaskPlanningRail,@@ -2992,7 +2991,7 @@ class JiuWenSwarmDeepAdapter:# 动态加载用户自定义的 Rail 扩展await self.load_user_rails()- async def _sync_prompt_attachments_for_request(self, session_id: str, invoke_turn_id: str) -> None:+ async def _sync_prompt_attachments_for_request(self, session_id: str) -> None:"""Hot-load prompt attachment files for the current request.Prompt attachment loading must not block the user request path. Failures are@@ -3008,28 +3007,10 @@ class JiuWenSwarmDeepAdapter: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("[JiuWenSwarmDeepAdapter] 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("[JiuWenSwarmDeepAdapter] 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()@@ -5097,8 +5078,7 @@ class JiuWenSwarmDeepAdapter:))inputs = dict(inputs)- inputs["_invoke_turn_id"] = request.request_id- await self._sync_prompt_attachments_for_request(session_id, request.request_id)+ await self._sync_prompt_attachments_for_request(session_id)result = await Runner.run_agent(agent=self._instance, inputs=inputs)except asyncio.CancelledError:logger.info(@@ -5111,7 +5091,6 @@ class JiuWenSwarmDeepAdapter:logger.error("[JiuWenSwarmDeepAdapter] Agent 任务执行异常: %s", e)raisefinally:- 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)@@ -5327,8 +5306,7 @@ class JiuWenSwarmDeepAdapter: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)+ await self._sync_prompt_attachments_for_request(session_id)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)@@ -5552,7 +5530,6 @@ class JiuWenSwarmDeepAdapter: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.pyindex 4f62d33e4a..eaf8c29f51 100644--- a/jiuwenswarm/server/runtime/prompt_attachment_loader.py+++ b/jiuwenswarm/server/runtime/prompt_attachment_loader.py@@ -1,9 +1,14 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""Prompt attachment directory loader for jiuwenswarm."""+"""Prompt attachment directory loader for jiuwenswarm.++This module is the jiuwenswarm-side file hot-load adapter. Before model calls,+it reads ``.md``/``.txt`` files from the current session's prompt attachment+directory, converts them into agent-core ``PromptAttachment`` objects, and+syncs them into the agent's ``PromptAttachmentManager``.+"""from __future__ import annotationsimport hashlib-import jsonimport loggingimport osimport re@@ -16,19 +21,15 @@ from typing import Any, Iterablefrom 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 AttachmentFiles in this directory are injected as dynamic prompt attachments for model calls.@@ -36,9 +37,7 @@ They are not user-uploaded attachments and are not written to long-termconversation 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.+- <session_id>/session/: hot-loaded prompt attachment files for one session.Markdown frontmatter is intentionally small: simple key-value fields and onelevel of metadata map are supported. Arrays, multiline strings, and full YAML@@ -79,11 +78,11 @@ def _is_reparse_path(path: Path) -> bool: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():+def _iter_safe_files(session_dir: Path, suffixes: frozenset[str]) -> Iterable[Path]:+ if not session_dir.exists() or not session_dir.is_dir():return- scope_root = scope_dir.resolve()- pending = [scope_dir]+ session_root = session_dir.resolve()+ pending = [session_dir]while pending:current = pending.pop()try:@@ -93,7 +92,7 @@ def _iter_safe_files(scope_dir: Path, suffixes: frozenset[str]) -> Iterable[Pathcontinuefor path in entries:try:- relative = path.relative_to(scope_dir)+ relative = path.relative_to(session_dir)except ValueError:continueif any(part.startswith(".") for part in relative.parts):@@ -106,8 +105,8 @@ def _iter_safe_files(scope_dir: Path, suffixes: frozenset[str]) -> Iterable[Pathexcept 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)+ if not _is_relative_to(resolved, session_root):+ logger.warning("[PromptAttachmentLoader] skip prompt attachment path outside session: %s", path)continueif path.is_dir():pending.append(path)@@ -115,13 +114,9 @@ def _iter_safe_files(scope_dir: Path, suffixes: frozenset[str]) -> Iterable[Pathyield 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}:+ if origin_source and origin_source != SESSION_SOURCE:result.setdefault("origin_source", origin_source)return result@@ -261,41 +256,36 @@ def _resolve_from_context(ctx: Any, *names: str) -> str | None:class PromptAttachmentFileStore:- """User-friendly file CRUD for prompt attachment directories."""+ """File CRUD helper for session 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":+ def bind_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 for_session(self, session_id: str) -> "PromptAttachmentSessionStore":+ return PromptAttachmentSessionStore(self, session_id=session_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,+ section: str | None = None,+ priority: int = 100,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",- )+ section_id = _safe_id_part(section) if section else self._section_from_name(name)+ path = self._file_path(session_id=session_id, name=name or section_id, suffix=".md")if path.exists():raise FileExistsError(f"prompt attachment already exists: {path}")frontmatter = self._frontmatter(+ section=section_id,priority=priority,kind=kind,source=source or _USER_SOURCE,@@ -303,15 +293,13 @@ class PromptAttachmentFileStore:)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)+ return self._item_from_file(path, session_id=session_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,@@ -320,18 +308,14 @@ class PromptAttachmentFileStore: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,- )+ path = self._resolve_id_or_name(id_or_name, session_id=session_id)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 old_meta.get("section") is not None:+ next_meta["section"] = old_meta["section"]if priority is not None:next_meta["priority"] = priorityif source is not None:@@ -345,86 +329,16 @@ class PromptAttachmentFileStore: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)+ return self._item_from_file(path, session_id=session_id)- 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,- )+ def get(self, id_or_name: str, *, session_id: str) -> PromptAttachment | None:+ path = self._resolve_id_or_name(id_or_name, session_id=session_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)+ return self._item_from_file(path, session_id=session_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,- )+ def delete(self, id_or_name: str, *, session_id: str) -> bool:+ path = self._resolve_id_or_name(id_or_name, session_id=session_id)if path is None:return Falsewith _path_lock(path):@@ -433,92 +347,32 @@ class PromptAttachmentFileStore: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,- ]+ def list(self, *, session_id: str) -> list[PromptAttachment]:+ session_dir = self._session_dir(session_id)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,- )+ for path in _iter_safe_files(session_dir, _TEXT_SUFFIXES):+ item = self._item_from_file(path, session_id=session_id)+ if item is not None:+ items.append(item)+ return sorted(items, key=lambda item: (item.priority, item.source or "", item.section))++ def _item_from_file(self, path: Path, *, session_id: str) -> PromptAttachment | None:+ raw = self._read_text_file(path, self._session_dir(session_id))+ if raw is None:+ return None+ meta, content = _parse_frontmatter(raw)+ session_dir = self._session_dir(session_id)+ section = _safe_id_part(str(meta.get("section") or self.relative_key(path, session_dir)))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()})+ metadata.update({"path": str(path), "relative_path": path.relative_to(session_dir).as_posix()})return PromptAttachment(- id=item_id,- scope=scope_value,+ id=self._item_id(session_id=session_id, section=section),+ section=section,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),+ priority=int(meta.get("priority") or 100),+ source=SESSION_SOURCE,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",)@@ -528,160 +382,75 @@ class PromptAttachmentFileStore: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:+ session_dir = self._session_dir(session_id)+ for path in _iter_safe_files(session_dir, _TEXT_SUFFIXES):+ relative_key = self.relative_key(path, session_dir)+ generated_id = f"session.{sanitize_session_id(session_id)}.{relative_key}"+ if id_or_name in {path.name, path.stem, relative_key, generated_id}: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+ item = self._item_from_file(path, session_id=session_id)+ if item is not None and item.id == id_or_name:+ return path+ return None- 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 _file_path(self, *, session_id: str, name: str, suffix: str) -> Path:+ relative = self._safe_relative_file_name(name=name, suffix=suffix)+ return self._session_dir(session_id) / relative- 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"+ def _session_dir(self, session_id: str) -> Path:+ return self.root / sanitize_session_id(session_id) / "session"++ @staticmethod+ def _item_id(*, session_id: str, section: str) -> str:+ return f"session.{sanitize_session_id(session_id)}.{_safe_id_part(section)}"++ @staticmethod+ def _section_from_name(name: str | None) -> str:+ if not name:+ return _safe_id_part(f"attachment_{time.time_ns()}_{threading.get_ident()}")+ raw_path = Path(name)+ parts = list(raw_path.with_suffix("").parts)+ return ".".join(_safe_id_part(part) for part in parts)@staticmethoddef _frontmatter(*,+ section: str,priority: int,kind: PromptAttachmentKind | str,source: str,metadata: dict[str, Any] | None,) -> dict[str, Any]:data: dict[str, Any] = {- "kind": _kind_value(kind),+ "section": section,"priority": priority,+ "kind": _kind_value(kind),"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)+ def _read_text_file(self, path: Path, session_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(session_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(session_dir).as_posix(),+ original_chars,+ len(text),+ )+ return text@staticmethoddef _coerce_kind(kind: PromptAttachmentKind | str) -> PromptAttachmentKind:@@ -695,126 +464,67 @@ class PromptAttachmentFileStore: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}):+ if raw_path.suffix.lower() not in _TEXT_SUFFIXES: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)- ])+ parts = []+ for index, part in enumerate(raw_path.parts):+ part_path = Path(part)+ if index == len(raw_path.parts) - 1:+ parts.append(f"{_safe_id_part(part_path.stem)}{part_path.suffix.lower()}")+ else:+ parts.append(_safe_id_part(part))+ return Path(*parts)++ @staticmethod+ def relative_key(path: Path, session_dir: Path) -> str:+ rel = path.relative_to(session_dir).with_suffix("")+ return ".".join(_safe_id_part(part) for part in rel.parts)class PromptAttachmentContextStore:- """Context-bound writer that hides session and turn ids from callers."""+ """Context-bound file writer that hides the session id from callers."""def __init__(self, store: PromptAttachmentFileStore, ctx: Any) -> None:self._store = storeself.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,- )+ return self._store.add_markdown(session_id=self.session_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 get(self, id_or_name: str) -> PromptAttachment | None:+ return self._store.get(id_or_name, session_id=self.session_id)- 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 delete(self, id_or_name: str) -> bool:+ return self._store.delete(id_or_name, session_id=self.session_id)- 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+ def list(self) -> list[PromptAttachment]:+ return self._store.list(session_id=self.session_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:+ def __init__(self, store: PromptAttachmentFileStore, *, session_id: str) -> None:self._store = storeself.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 add_markdown(self, **kwargs: Any) -> PromptAttachment:+ return self._store.add_markdown(session_id=self.session_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 get(self, id_or_name: str) -> PromptAttachment | None:+ return self._store.get(id_or_name, session_id=self.session_id)- 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 delete(self, id_or_name: str) -> bool:+ return self._store.delete(id_or_name, session_id=self.session_id)- 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+ def list(self) -> list[PromptAttachment]:+ return self._store.list(session_id=self.session_id)class PromptAttachmentLoader:@@ -825,15 +535,15 @@ class PromptAttachmentLoader:self.max_file_chars = max_file_charsself.file_store = PromptAttachmentFileStore(self.root, max_file_chars=max_file_chars)- def for_context(self, ctx: Any) -> PromptAttachmentContextStore:+ def bind_context(self, ctx: Any) -> PromptAttachmentContextStore:"""Return a context-bound file writer facade."""- return self.file_store.for_context(ctx)+ return self.file_store.bind_context(ctx)- def for_session(self, session_id: str, *, invoke_turn_id: str | None = None) -> PromptAttachmentSessionStore:+ def for_session(self, session_id: str) -> PromptAttachmentSessionStore:"""Return a session-bound file writer facade."""- return self.file_store.for_session(session_id, invoke_turn_id=invoke_turn_id)+ return self.file_store.for_session(session_id)def ensure_layout(self) -> None:"""Create the root prompt attachment layout."""@@ -851,40 +561,11 @@ class PromptAttachmentLoader: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."""+ """Load prompt attachments for one jiuwenswarm session."""- 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,- )+ return self.file_store.list(session_id=session_id)- async def sync_to_agent(- self,- agent: Any,- *,- session_id: str,- invoke_turn_id: str,- ) -> None:+ async def sync_to_agent(self, agent: Any, *, session_id: str) -> None:"""Synchronize current prompt attachment files to a DeepAgent instance.Loader failures are intentionally non-fatal. User requests must continue@@ -899,31 +580,15 @@ class PromptAttachmentLoader: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)returnlogger.info(- "[PromptAttachmentLoader] sync prompt attachments: session_id=%s invoke_turn_id=%s session=%d turn=%d",+ "[PromptAttachmentLoader] sync prompt attachments: session_id=%s session=%d",session_id,- invoke_turn_id,len(session_attachments),- len(turn_attachments),)try:@@ -931,177 +596,17 @@ class PromptAttachmentLoader: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-@staticmethoddef 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)+ def relative_key(path: Path, session_dir: Path) -> str:+ return PromptAttachmentFileStore.relative_key(path, session_dir)__all__ = [@@ -1111,6 +616,5 @@ __all__ = ["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.pyindex a8ba25b781..bd0c9cb91a 100644--- a/tests/system_tests/test_project_memory.py+++ b/tests/system_tests/test_project_memory.py@@ -75,7 +75,7 @@ def _make_ctx(agent: MagicMock, session_id: str = "sess1") -> SimpleNamespace:async def _project_memory_attachment(agent: MagicMock, session_id: str = "sess1"):- items = await agent.prompt_attachment_manager.collect_for_turn(session_id, "turn1")+ items = await agent.prompt_attachment_manager.collect_for_session(session_id)project_items = [item for item in items if item.id.endswith(".project_memory")]return project_items[-1] if project_items else Nonediff --git a/tests/unit_tests/agentserver/rails/test_project_memory_rail.py b/tests/unit_tests/agentserver/rails/test_project_memory_rail.pyindex a13a063c0c..dc862036b4 100644--- a/tests/unit_tests/agentserver/rails/test_project_memory_rail.py+++ b/tests/unit_tests/agentserver/rails/test_project_memory_rail.py@@ -74,7 +74,7 @@ def _make_ctx(agent: MagicMock, session_id: str = "sess1") -> SimpleNamespace:async def _project_memory_attachment(agent: MagicMock, session_id: str = "sess1"):- items = await agent.prompt_attachment_manager.collect_for_turn(session_id, "turn1")+ items = await agent.prompt_attachment_manager.collect_for_session(session_id)project_items = [item for item in items if item.id.endswith(".project_memory")]return project_items[-1] if project_items else Nonediff --git a/tests/unit_tests/agentserver/test_prompt_attachment_loader.py b/tests/unit_tests/agentserver/test_prompt_attachment_loader.pyindex 6c5edfafef..3c235e6ad7 100644--- a/tests/unit_tests/agentserver/test_prompt_attachment_loader.py+++ b/tests/unit_tests/agentserver/test_prompt_attachment_loader.py@@ -7,16 +7,12 @@ import pytestfrom openjiuwen.core.foundation.llm import SystemMessage, UserMessagefrom 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,)@@ -54,6 +50,7 @@ def test_loader_ensure_layout_and_loads_stable_order_kind_and_ids(tmp_path):assert (root / "README.md").exists()readme = (root / "README.md").read_text(encoding="utf-8")assert "not user-uploaded attachments" in readme+ assert "turn" not in readme.lower()assert all(ord(char) < 128 for char in readme)assert [item.id for item in items] == ["session.sess1.diagnostics",@@ -82,59 +79,28 @@ def test_loader_skips_empty_files_and_truncates_large_files(tmp_path):assert "truncated by jiuwenswarm loader" in items[0].content-def test_user_friendly_for_context_add_markdown_hides_session_and_turn(tmp_path):+def test_context_store_add_update_get_delete_and_list_use_bound_session(tmp_path):root = tmp_path / "prompt_attachment"loader = PromptAttachmentLoader(root)- ctx = SimpleNamespace(session_id="sess1", invoke_turn_id="req1")+ store = loader.bind_context(SimpleNamespace(session_id="sess1"))+ created = store.add_markdown(name="hint.md", content="session hint", priority=42)- 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, content="session hint v2")+ listed = store.list()- updated = store.update_markdown(- created.id,- scope=PromptAttachmentScope.TURN,- content="turn hint v2",- )- listed = store.list(scope=PromptAttachmentScope.TURN)+ assert created.id == "session.sess1.hint"+ assert updated.content == "session hint v2"+ assert updated.priority == 42+ assert store.get(created.id).content == "session hint v2"+ assert [item.id for item in listed] == ["session.sess1.hint"]+ assert store.delete(created.id) is True+ assert store.get(created.id) is None- 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):+def test_file_store_add_markdown_validates_paths(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):@@ -145,7 +111,7 @@ 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(+ created = session_store.add_markdown(name="release.md",content="old content",priority=80,@@ -172,101 +138,13 @@ def test_update_markdown_preserves_frontmatter_and_merges_metadata(tmp_path):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")+ first = store.add_markdown(content="one")+ second = store.add_markdown(content="two")assert first.id != second.idassert [item.content for item in store.list()] == ["one", "two"]@@ -311,36 +189,6 @@ def test_loader_skips_reparse_marked_prompt_attachment_paths(tmp_path, monkeypatassert [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,- ) == []--@pytest.mark.asyncioasync def test_sync_to_agent_hot_reloads_session_modify_and_delete(tmp_path):root = tmp_path / "prompt_attachment"@@ -351,103 +199,34 @@ async def test_sync_to_agent_hot_reloads_session_modify_and_delete(tmp_path):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")+ await loader.sync_to_agent(agent, session_id="sess1")+ items = await agent.prompt_attachment_manager.collect_for_session("sess1")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")+ await loader.sync_to_agent(agent, session_id="sess1")+ items = await agent.prompt_attachment_manager.collect_for_session("sess1")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")+ await loader.sync_to_agent(agent, session_id="sess1")+ items = await agent.prompt_attachment_manager.collect_for_session("sess1")assert items == []@pytest.mark.asyncio-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):+async def test_file_loaded_attachments_render_and_inject(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")+ await loader.sync_to_agent(agent, session_id="sess1")manager = agent.prompt_attachment_manager- rendered = manager.render(await manager.collect_for_turn("sess1", "req1"))+ rendered = manager.render(await manager.collect_for_session("sess1"))messages = [SystemMessage(content="STATIC_SYSTEM_PROMPT"),UserMessage(content="original query"),@@ -458,59 +237,28 @@ async def test_file_loaded_attachments_render_inject_and_turn_cleanup(tmp_path):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].contentassert "original query" in injected[-1].contentassert "<system-reminder>" in injected[-1].contentassert "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"]@pytest.mark.asyncio-async def test_flat_turn_files_are_ignored(tmp_path):+async def test_sync_to_agent_read_failure_does_not_block_or_clear_old_state(tmp_path, monkeypatch):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")+ session_dir = root / "sess1" / "session"+ session_dir.mkdir(parents=True)+ (session_dir / "runtime.md").write_text("v1", encoding="utf-8")- req2_dir = root / "sess1" / "turn" / "req2"- req2_dir.mkdir(parents=True)- (req2_dir / "request_context.md").write_text("turn 2", encoding="utf-8")+ await loader.sync_to_agent(agent, session_id="sess1")+ assert await agent.prompt_attachment_manager.list_by_filter(source=SESSION_SOURCE, session_id="sess1")- def fail_read(*args, **kwargs):+ def fail_list(*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")+ monkeypatch.setattr(loader, "load_session_attachments", fail_list)+ await loader.sync_to_agent(agent, session_id="sess1")- 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 == []+ items = await agent.prompt_attachment_manager.collect_for_session("sess1")+ assert [item.content for item in items] == ["v1"]diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pyindex 2a26bfda82..0288e10052 100644--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -6,10 +6,7 @@ import pytestfrom openjiuwen.core.foundation.llm import Modelfrom openjiuwen.core.single_agent.rail.base import AgentCallbackContextfrom openjiuwen.harness.prompts.prompt_attachment_manager import (- PromptAttachment,- PromptAttachmentKind,PromptAttachmentManager,- PromptAttachmentScope,)from openjiuwen.harness.prompts import PromptSection, SystemPromptBuilder@@ -87,7 +84,7 @@ async def test_runtime_time_section_participates_in_priority_order():agent=agent,inputs=None,session=_FakeSession(),- extra={"_invoke_turn_id": "turn1"},+ extra={},)await runtime_rail.before_model_call(ctx)@@ -117,7 +114,7 @@ async def test_runtime_dynamic_sections_go_to_prompt_attachment_when_manager_avaagent=agent,inputs=None,session=_FakeSession(),- extra={"_invoke_turn_id": "turn1"},+ extra={},)await runtime_rail.before_model_call(ctx)@@ -128,11 +125,11 @@ async def test_runtime_dynamic_sections_go_to_prompt_attachment_when_manager_avaassert "# Browser Tool Policy" not in promptassert "# Environment" in prompt- items = await agent.prompt_attachment_manager.collect_for_turn("sess1", "turn1")+ items = await agent.prompt_attachment_manager.collect_for_session("sess1")assert [item.id for item in items] == [- "turn.sess1.turn1.language_output",- "turn.sess1.turn1.runtime",- "turn.sess1.turn1.browser_tool_policy",+ "session.sess1.language_output",+ "session.sess1.runtime",+ "session.sess1.browser_tool_policy",]rendered = agent.prompt_attachment_manager.render(items)assert "model-x" in rendered@@ -158,72 +155,19 @@ async def test_runtime_git_status_attachment_clears_when_git_context_disappears(agent=agent,inputs=None,session=_FakeSession(),- extra={"_invoke_turn_id": "turn1"},+ extra={},)await runtime_rail.before_model_call(ctx)- session_items = await agent.prompt_attachment_manager.list_by_filter(session_id="sess1", scope="session")+ session_items = await agent.prompt_attachment_manager.list_by_filter(session_id="sess1")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")+ session_items = await agent.prompt_attachment_manager.list_by_filter(session_id="sess1")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 = JiuWenSwarmDeepAdapter.__new__(JiuWenSwarmDeepAdapter)- 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.asyncioasync def test_runtime_prompt_uses_runtime_cwd_over_stale_trusted_dir(tmp_path):builder = SystemPromptBuilder(language="en")@@ -244,14 +188,14 @@ async def test_runtime_prompt_uses_runtime_cwd_over_stale_trusted_dir(tmp_path):agent=agent,inputs=None,session=_FakeSession(),- extra={"_invoke_turn_id": "turn1"},+ extra={},)await runtime_rail.before_model_call(ctx)prompt = builder.build()assert "Current project directory" not in promptrendered = agent.prompt_attachment_manager.render(- await agent.prompt_attachment_manager.collect_for_turn("sess1", "turn1")+ await agent.prompt_attachment_manager.collect_for_session("sess1"))assert "Current project directory" in renderedassert str(current_dir) in rendered@@ -281,14 +225,14 @@ async def test_runtime_prompt_language_output_prefers_rail_language_over_runtimeagent=agent,inputs=None,session=_FakeSession(),- extra={"_invoke_turn_id": "turn1"},+ extra={},)await runtime_rail.before_model_call(ctx)prompt = builder.build()assert "Always respond in Chinese." not in promptrendered = agent.prompt_attachment_manager.render(- await agent.prompt_attachment_manager.collect_for_turn("sess1", "turn1")+ await agent.prompt_attachment_manager.collect_for_session("sess1"))assert "Always respond in Chinese." in renderedassert "Always respond in English." not in rendereddiff --git a/uv.lock b/uv.lockindex b067377426..c5d6bc5ab1 100644--- a/uv.lock+++ b/uv.lock@@ -1179,6 +1179,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl", hash = "sha256:d2ceafaad1b3457968ed14efa28798162f1638dbb5d2a6868a2db002a5ee39a4", size = 202595, upload-time = "2026-03-27T19:11:13.595Z" },]+[[package]]+name = "gitcode-api"+version = "1.3.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "httpx" },+]+sdist = { url = "https://files.pythonhosted.org/packages/6b/c6/764e504be1b9d09bfb66c758eb74a609859fb0c6cd29aaa9b2e9cfb749ef/gitcode_api-1.3.0.tar.gz", hash = "sha256:b97b21f2f41e2448362565b6f7f45112ae82ac1e1004aa45caa64b240fcc099d", size = 94628, upload-time = "2026-06-08T16:35:47.343Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/42/f3/dc4b871add178a0366ddccc6abd5b7bf177d6c0ae5b78c2db36ae916fe40/gitcode_api-1.3.0-py3-none-any.whl", hash = "sha256:951fcb130185cf33bf423c2052c86d64b594f8ab57fc04e2ab944bb9124867f3", size = 94947, upload-time = "2026-06-08T16:35:45.948Z" },+]+[[package]]name = "google-adk"version = "2.1.0"@@ -2642,7 +2654,7 @@ wheels = [[[package]]name = "openjiuwen"version = "0.1.14"-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#4eccf9ee99daced398525bec8e941921d8843cd3" }+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#c685269632704e7b95024acc4eb1393daea51f20" }dependencies = [{ name = "aiofiles" },{ name = "aiohttp" },@@ -2655,6 +2667,7 @@ dependencies = [{ name = "docx2txt" },{ name = "fastmcp" },{ name = "filelock" },+ { name = "gitcode-api" },{ name = "json-repair" },{ name = "loguru" },{ name = "mcp" },