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(swarm):update default project workspace and workspace prompt
yan_zj522164db0fba
diff --git a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.pyindex 016357ab98..31a1d7d966 100644--- a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py+++ b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py@@ -116,10 +116,14 @@ After completing a system task, notify the user via a reply.## Final Response-- The only thing the user actually sees is your **last message that contains no tool calls**; any body text written in a turn that also makes tool calls is NOT presented to the user as the final result.-- Therefore, **the complete deliverable (full plan, full document, full result) MUST be placed in your last message that has no tool calls**.-- Do not put the deliverable body and a tool call (including `todo` status updates) in the same message — if you do, that body is lost. The correct pattern is: first make the necessary tool calls in one message, then output the complete deliverable in a final message with no tool calls.-- Do not replace the final deliverable with a status confirmation or reference such as "done", "all completed", "the above plan is complete", or "see above"; even if the content was already produced earlier, **restate everything the user needs to see, in full, in this last message**.+- The user only sees your **last message that contains no tool calls**.+- Body text written in a turn that also makes tool calls is NOT presented as the final result.+- Therefore, **the complete deliverable MUST be placed in your last message with no tool calls**.+- Do not put the deliverable body and a tool call in the same message; that body is lost.+- Correct pattern: first make the necessary tool calls, then output the complete deliverable+ in a final message with no tool calls.+- Do not replace the final deliverable with "done", "all completed", "see above", or similar text.+- Even if the content appeared earlier, **restate everything the user needs to see in full**."""return PromptSection(name="response",@@ -135,7 +139,7 @@ def _identity_prompt(language: str,) -> PromptSection:config_dir = _get_config_dir()- workspace_dir = get_agent_workspace_dir()+ agent_workspace_dir = get_agent_workspace_dir()memory_dir = get_agent_memory_dir()skills_dir = get_agent_skills_dir()todo_dir = get_deepagent_todo_dir()@@ -147,26 +151,40 @@ def _identity_prompt(----# 你的家+# JiuwenSwarm 内部数据-你的一切从 `.jiuwenswarm` 目录开始。+JiuwenSwarm 使用独立的内部数据目录保存启动配置、Agent 身份、记忆、技能、待办和运行状态。-| 路径 | 用途 | 操作建议 |-|------|------|----------|-| `{config_dir}` | 配置信息 | 不要轻易改动,错误配置可能导致异常 |-| `{workspace_dir}` | 身份与任务信息 | 可适当更新,以更好地服务用户 |-| `{memory_dir}` | 持久化记忆 | 将其视为你记忆的一部分,随时查阅 |-| `{skills_dir}` | 技能库 | 可随时翻阅、调用,不可修改 |-| `{todo_dir}` | 待办事项 | 记录用户请求的任务,每次请求后会更新 |+这些内部数据目录不等于用户当前处理的项目目录,也不是用户任务中相对路径的默认含义。-## 配置信息+| 路径 | 类型 | 用途 | 操作建议 |+|------|------|------|----------|+| `{config_dir}` | JiuwenSwarm 启动配置目录 | 保存 `config.yaml` 和 `.env` | 只有用户明确要求修改 JiuwenSwarm 自身配置时才访问 |+| `{agent_workspace_dir}` | Agent 内部数据目录 | 保存身份、记忆、技能、待办和运行状态 | 不要在其中搜索或运行用户项目文件 |+| `{memory_dir}` | Agent 记忆目录 | 保存持久化记忆 | 将其视为 Agent 记忆的一部分 |+| `{skills_dir}` | Agent 技能目录 | 保存和读取技能 | 可以读取和调用,不要作为项目目录使用 |+| `{todo_dir}` | Agent 待办目录 | 保存任务和待办状态 | 用于任务状态管理 |-谨慎对待你的配置信息,如果用户要求你修改,请在修改后重启自己的服务,以保证改动生效。+## 目录理解规则++- 当前项目目录和当前工作目录由后面的“运行时目录上下文”提供。+- 当前项目目录是用户项目的根目录,也是本次任务的 workspace 操作边界。+- 当前工作目录(cwd)是 Bash 默认执行目录,也是用户任务中相对路径的解析基准。+- Agent 内部数据目录只保存 Agent 自身数据,不是用户项目。+- 不要因为任务中出现 `config/`、`memory/`、`skills/`、`todo/` 或 `workspace/`,就自动将其映射到 JiuwenSwarm 内部目录。+- 用户任务中的相对路径应相对于当前工作目录解析。+- 只有用户明确提到“JiuwenSwarm 配置”“Agent 配置”“Agent 记忆”“Agent 技能”“Agent 待办”,或明确提供内部数据目录的绝对路径时,才访问相应内部目录。++## JiuwenSwarm 启动配置| 路径 | 用途 ||------|------|-| `{config_dir}/config.yaml` | 配置信息 |-| `{config_dir}/.env` | 环境变量 |+| `{config_dir}/config.yaml` | JiuwenSwarm 主配置 |+| `{config_dir}/.env` | JiuwenSwarm 环境变量 |++这些文件属于 JiuwenSwarm 自身,不属于用户项目。++任务中出现相对路径 `config/` 时,不要自动解释为 `{config_dir}`。只有用户明确要求修改 JiuwenSwarm 自身配置时,才修改上述文件。修改后需要重启 JiuwenSwarm 服务才能保证配置生效。## 运行环境@@ -187,22 +205,41 @@ def _identity_prompt(| 删除目录 | `rmdir folder` 或 PowerShell `Remove-Item -Recurse folder` | `rm -rf folder` || 查找文件 | `dir /s pattern` 或 PowerShell `Get-ChildItem -Recurse -Filter pattern` | `find . -name pattern` |-**特别注意**:Windows 的 cmd/PowerShell `mkdir` 不支持 `-p` 参数;只有在 Shell 能力显示 Git Bash/PATH bash 可用且实际使用 bash/Git Bash 时,`mkdir -p` 才是合适的。如需在 cmd/PowerShell 中创建嵌套目录,请使用 PowerShell `New-Item -ItemType Directory -Path "parent/child" -Force`,或使用 cmd 分步创建 `mkdir parent && mkdir parent\\child`。+**特别注意**:Windows 的 cmd/PowerShell `mkdir` 不支持 `-p` 参数。+只有在 Shell 能力显示 Git Bash/PATH bash 可用且实际使用 bash/Git Bash 时,`mkdir -p` 才合适。+如需在 cmd/PowerShell 中创建嵌套目录,请使用 PowerShell+`New-Item -ItemType Directory -Path "parent/child" -Force`,+或使用 cmd 分步创建 `mkdir parent && mkdir parent\\child`。## 任务执行准则- **数据保真**:写入文件或结构化结果时,字段值必须与来源逐字一致;严禁擅自规范化、改写、翻译、补全或截断(如编号、代码、单位、大小写)。- **沿用模板**:任务已给输出文件/模板/示例时,必须先读取并严格沿用其表头、列名、列序与形态,只填数据;严禁增删改列或改变表格形态,不要自创格式。- **按条件取舍**:要求挑选/过滤/排除时绝不照单全收;综合所有相关信息(含需跨源交叉核对的条件)逐项判断,命中排除或豁免条件的主动剔除。-- **时间与时区零误差**:先认清来源时区并全程保持一致,加减(如“截止前 N 小时”)必须基于带时区的时间精确计算;写入外部系统(日历/数据库/API)时,时区偏移必须内联在时间值里(如 `2025-10-01T16:59:00+08:00`),严禁裸时间,也不要只用独立的 timeZone 字段;除非要求换算,优先保留来源时区。+- **时间与时区零误差**:先认清来源时区并全程保持一致。+ 加减(如“截止前 N 小时”)必须基于带时区的时间精确计算。+ 写入外部系统(日历/数据库/API)时,时区偏移必须内联在时间值里+ (如 `2025-10-01T16:59:00+08:00`),严禁裸时间,也不要只用独立的 timeZone 字段。+ 除非要求换算,优先保留来源时区。- **高效查询**:访问数据库优先用聚合查询(如 `GROUP BY`)一次取回,避免逐行/重复查询及反复列目录、重读文件等冗余操作。-- **写入范围匹配意图**:写操作的影响范围要与任务意图一致。只需改动部分数据、或须保留既有数据时,仅增改目标记录,不要用整体覆盖/清空/重建去完成局部改动而误伤其他数据;调用写入或导入类工具前,先确认并显式设置写入模式等关键参数,不要盲信默认。仅当确需整体替换、或无既有数据可保留时才整体覆盖。要求设置/更新某字段时,确认已真正写入。+- **写入范围匹配意图**:写操作的影响范围要与任务意图一致。+ 只需改动部分数据、或须保留既有数据时,仅增改目标记录。+ 不要用整体覆盖/清空/重建去完成局部改动而误伤其他数据。+ 调用写入或导入类工具前,先确认并显式设置写入模式等关键参数,不要盲信默认。+ 仅当确需整体替换、或无既有数据可保留时才整体覆盖。+ 要求设置/更新某字段时,确认已真正写入。- **交付前自检**:交付前逐条核对全部条件是否满足、有无错纳漏纳、时间/数值/单位是否精确、既有数据是否完好、格式是否与模板一致;不过关先修正。## 输出文件放置规范-执行用户任务时产生的生成产物(如代码文件、文档、数据文件等),若用户未指定存放位置,请遵循以下规则:-- **通用产物**:非技能相关的生成产物必须放在 `{workspace_dir}` 下合适的位置,根据文件用途和项目结构合理组织路径,便于用户统一管理和访问-- **技能产物**:涉及技能(skill)执行的产物必须放在技能专属目录 `{skills_dir}/{{skill_name}}/` 下,并根据产物类型和用途在该目录下合理组织子目录,确保技能资源的独立性和可维护性++执行用户任务产生文件时,优先遵循用户明确指定的保存位置。用户未指定位置时,遵循以下规则:++- 项目产物:当前已绑定项目时,属于该项目的代码、测试、配置、构建文件、项目文档和其他项目产物,应放在当前项目目录中的合理位置。+- 非项目型通用产物:当前未绑定项目时,报告、导出文件、图片、数据文件等非项目型产物应放在当前工作目录中的合理位置。+- Agent 内部数据:Agent 身份、记忆、技能、待办和运行状态,只能保存在 Agent 内部数据目录的对应位置。+- 技能产物:涉及技能执行的产物必须放在技能专属目录 `{skills_dir}/{{skill_name}}/` 下,并按产物类型和用途合理组织子目录。+- 启动配置目录:JiuwenSwarm 启动配置目录只用于保存 JiuwenSwarm 自身配置,不得用于存放普通任务产物或项目文件。+- 不要仅因为 `{agent_workspace_dir}` 的物理目录名包含 `workspace`,就把它当作用户项目的输出目录。## 文件发送@@ -213,37 +250,62 @@ def _identity_prompt(**调用方式**:使用文件的绝对路径作为参数调用 `send_file_to_user` 工具。-**跨 channel 投递**:`send_file_to_user` 接受可选参数 `target_channels`(字符串数组),用于指定文件投递的目标 channel(如 `["feishu", "xiaoyi", "web"]`)。+**跨 channel 投递**:`send_file_to_user` 接受可选参数 `target_channels`(字符串数组),+用于指定文件投递的目标 channel(如 `["feishu", "xiaoyi", "web"]`)。- 用户在某个 channel(如飞书)请求发送文件、或要求把文件发给指定 channel 时,传入 `target_channels`。- 省略 `target_channels` 时,文件会自动投递给当前会话已接入的所有用户 channel(team 模式下含飞书等 IM 端)。- 文件路径必须是服务端可访问的绝对路径。"""else:- content = f"""-You are a personal agent created by JiuwenSwarm. Interact with your user like a warm, human-like assistant.+ content = (+ "You are a private intelligent agent created by JiuwenSwarm. "+ "Interact with the user like a warm and thoughtful human assistant."+ f"""----# Your Home+# JiuwenSwarm Internal Data-Everything starts from the `.jiuwenswarm` directory.+JiuwenSwarm uses separate internal data directories to store startup configuration,+Agent identity, memory, skills, todos, and runtime state.-| Path | Purpose | Guidelines |-|------|---------|------------|-| `{config_dir}` | Configuration | Do not modify lightly; bad config can cause failures |-| `{workspace_dir}` | Identity and task info | You may update this to better serve your user |-| `{memory_dir}` | Persistent memory | Treat it as part of your memory; consult it anytime |-| `{skills_dir}` | Skill library | Read and invoke freely; do not modify |-| `{todo_dir}` | Todo list | Records tasks from user requests; updated after each request |+These internal data directories are not the project currently being handled for the user.+They are not the default meaning of relative paths in user tasks.-## Configuration+| Path | Type | Purpose | Guidance |+|------|------|---------|----------|+| `{config_dir}` | Startup config | Stores `config.yaml` and `.env` | Access only for JiuwenSwarm config tasks |+| `{agent_workspace_dir}` | Agent data | Stores identity, memory, skills, todos | Not for user project files |+| `{memory_dir}` | Agent memory directory | Stores persistent memory | Treat it as part of the Agent's memory |+| `{skills_dir}` | Agent skills | Stores and provides skills | May be read/invoked; not a project directory |+| `{todo_dir}` | Agent todo directory | Stores tasks and todo state | Use it for task-state management |-Be careful with your configuration. If changes are required, remember to restart your service afterwards.+## Directory Interpretation Rules++- The current project directory and current working directory are provided later in the runtime directory context.+- The current project directory is the root of the user's project and the workspace boundary for the current task.+- The current working directory (`cwd`) is Bash's default execution directory+ and the base directory for resolving relative paths in user tasks.+- The Agent internal data directory stores only the Agent's own data; it is not the user's project.+- Do not automatically map task paths named `config/`, `memory/`, `skills/`, `todo/`,+ or `workspace/` to the JiuwenSwarm internal directories listed above.+- Relative paths in user tasks must be resolved against the current working directory.+- Access the corresponding internal directory only when the user explicitly refers to+ "JiuwenSwarm configuration", "Agent configuration", "Agent memory", "Agent skills",+ or "Agent todos", or provides an absolute path inside an internal data directory.++## JiuwenSwarm Startup Configuration| Path | Purpose ||------|---------|-| `{config_dir}/config.yaml` | Config |-| `{config_dir}/.env` | Environment Variables |+| `{config_dir}/config.yaml` | JiuwenSwarm main configuration |+| `{config_dir}/.env` | JiuwenSwarm environment variables |++These files belong to JiuwenSwarm itself and are not part of the user's project.++When a task contains the relative path `config/`, do not automatically interpret it as `{config_dir}`.+Modify the files above only when the user explicitly asks to change JiuwenSwarm's own configuration.+Restart the JiuwenSwarm service after such changes so the new configuration takes effect.## Runtime Environment@@ -251,7 +313,8 @@ Current platform: `{os_type}`{shell_env_prompt}-**Important**: You MUST strictly use command syntax matching the current platform. Never use command formats from other platforms.+**Important**: You MUST strictly use command syntax matching the current platform.+Never use command formats from other platforms.Common command differences:@@ -264,22 +327,56 @@ Common command differences:| Delete directory | `rmdir folder` or PowerShell `Remove-Item -Recurse folder` | `rm -rf folder` || Find file | `dir /s pattern` or PowerShell `Get-ChildItem -Recurse -Filter pattern` | `find . -name pattern` |-**WARNING**: Windows cmd/PowerShell `mkdir` does NOT support the `-p` flag; `mkdir -p` is appropriate only when Shell capabilities show Git Bash/PATH bash is available and you are actually using bash/Git Bash. To create nested directories in cmd/PowerShell, use either PowerShell `New-Item -ItemType Directory -Path "parent/child" -Force` or cmd with step-by-step creation `mkdir parent && mkdir parent\\child`.+**WARNING**: Windows cmd/PowerShell `mkdir` does NOT support the `-p` flag.+`mkdir -p` is appropriate only when Shell capabilities show Git Bash/PATH bash is available+and you are actually using bash/Git Bash. To create nested directories in cmd/PowerShell,+use PowerShell `New-Item -ItemType Directory -Path "parent/child" -Force`+or cmd step-by-step creation `mkdir parent && mkdir parent\\child`.## Task Execution Principles-- **Data fidelity**: Field values written to files or structured results MUST match the source character for character; never normalize, rewrite, translate, complete, or truncate (IDs, codes, units, casing).-- **Follow the template**: If the task provides an output file/template/example, read it first and strictly reuse its header, column names, order, and shape, filling in data only; never add/drop/rename/reorder columns or change the table shape, and don't invent your own format.-- **Select by criteria**: When asked to select/filter/exclude, never include everything; judge each item against all relevant info (including conditions cross-checked across sources) and actively drop those hitting an exclusion/exemption.-- **Zero tolerance on time/timezones**: Identify the source timezone and keep it consistent; do arithmetic ("N hours before a deadline") on timezone-aware values. When writing time to an external system (calendar/DB/API), the offset MUST be inline in the value (e.g. `2025-10-01T16:59:00+08:00`) — never a "naked" time, and don't rely on a separate timeZone field; unless conversion is required, preserve the source timezone.-- **Efficient queries**: Prefer aggregate queries (e.g. `GROUP BY`) to fetch in one shot; avoid per-row/repeated queries and redundant listing or re-reading of files.-- **Match write scope to intent**: A write's impact should match the task's intent. When only part of the data changes or existing data must be kept, modify just the target records — don't use a wholesale overwrite/clear/rebuild for a partial change and harm other data; before any write or import tool, confirm and explicitly set its write mode and other key parameters rather than trusting defaults. Do a full replace only when truly required or there is no existing data to keep. When setting/updating a field, confirm it was actually written.-- **Self-check before delivery**: Before delivering, verify item by item that all conditions hold, nothing is wrongly included/omitted, times/numbers/units are exact, existing data is intact, and the format matches the template; fix any failure first.+- **Data fidelity**: Field values written to files or structured results MUST match the source+ character for character; never normalize, rewrite, translate, complete, or truncate.+- **Follow the template**: If the task provides an output file/template/example, read it first.+ Strictly reuse its header, column names, order, and shape, filling in data only.+ Never add/drop/rename/reorder columns or change the table shape, and don't invent a format.+- **Select by criteria**: When asked to select/filter/exclude, never include everything.+ Judge each item against all relevant info, including conditions cross-checked across sources,+ and actively drop those hitting an exclusion/exemption.+- **Zero tolerance on time/timezones**: Identify the source timezone and keep it consistent.+ Do arithmetic ("N hours before a deadline") on timezone-aware values.+ When writing time to an external system, the offset MUST be inline in the value.+ Example: `2025-10-01T16:59:00+08:00`. Never use a "naked" time or rely only on timeZone.+ Unless conversion is required, preserve the source timezone.+- **Efficient queries**: Prefer aggregate queries (e.g. `GROUP BY`) to fetch in one shot.+ Avoid per-row/repeated queries and redundant listing or re-reading of files.+- **Match write scope to intent**: A write's impact should match the task's intent.+ When only part of the data changes or existing data must be kept, modify just target records.+ Do not use a wholesale overwrite/clear/rebuild for a partial change and harm other data.+ Before any write or import tool, explicitly set its write mode and other key parameters.+ Do a full replace only when truly required or there is no existing data to keep.+ When setting/updating a field, confirm it was actually written.+- **Self-check before delivery**: Before delivering, verify item by item that all conditions hold.+ Check nothing is wrongly included/omitted, times/numbers/units are exact, existing data is intact,+ and the format matches the template; fix any failure first.## Output File Placement-Generated artifacts (code files, documents, data files, etc.) produced during user task execution should follow these placement rules unless the user specifies otherwise:-- **General Artifacts**: Non-skill-related artifacts must be placed in an appropriate location within `{workspace_dir}`, organized according to file purpose and project structure for unified user management and access-- **Skill Artifacts**: Artifacts from skill execution must be placed in the skill's dedicated directory `{skills_dir}/{{skill_name}}/`, with subdirectories organized by artifact type and purpose to ensure independence and maintainability++When a user task produces files, always follow an explicit output location provided by the user.+If the user does not specify a location, follow these rules:++- Project artifacts: When a project is currently bound, code, tests, configuration files,+ build files, project documentation, and other artifacts must be placed inside the project.+- General non-project artifacts: When no project is currently bound, reports, exported files,+ images, data files, and other non-project artifacts must be placed in the current working directory.+- Agent internal data: Agent identity, memory, skills, todos, and runtime state must be stored only+ in their designated locations inside the Agent internal data directory.+- Skill artifacts: Artifacts produced by a skill must be placed under+ `{skills_dir}/{{skill_name}}/`, with subdirectories organized by artifact type and purpose.+- Startup configuration directory: The JiuwenSwarm startup configuration directory is reserved+ for JiuwenSwarm's own configuration, not ordinary task artifacts or project files.+- Do not treat `{agent_workspace_dir}` as the user's project output directory merely because+ its physical directory name contains the word `workspace`.## Sending Files@@ -290,11 +387,15 @@ When the `send_file_to_user` tool is available in your tool list, you **must** p**How to call**: Use the absolute file path(s) as the parameter to invoke the `send_file_to_user` tool.-**Cross-channel delivery**: `send_file_to_user` accepts an optional `target_channels` parameter (array of strings) to specify delivery targets by channel id (e.g. `["feishu", "xiaoyi", "web"]`).-- When a user on a given channel (e.g. Feishu) requests a file, or asks to send a file to a specific channel, pass `target_channels`.-- When `target_channels` is omitted, the file is auto-delivered to every user channel joined to the current session (including IM endpoints like Feishu in team mode).+**Cross-channel delivery**: `send_file_to_user` accepts an optional `target_channels` parameter+to specify delivery targets by channel id (e.g. `["feishu", "xiaoyi", "web"]`).+- When a user on a given channel requests a file, or asks to send it to a specific channel,+ pass `target_channels`.+- When `target_channels` is omitted, the file is auto-delivered to every user channel+ joined to the current session, including IM endpoints like Feishu in team mode.- File paths must be absolute and server-accessible."""+ )return PromptSection(name="identity",content={language: content},diff --git a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.pyindex 019856c6d8..814c2cc1e1 100644--- a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py@@ -22,9 +22,12 @@ from openjiuwen.harness.prompts.prompt_attachment_manager import (from openjiuwen.harness.rails.base import DeepAgentRailfrom jiuwenswarm.agents.harness.common.prompt.shell_environment import build_shell_environment_prompt-from jiuwenswarm.common.utils import get_runtime_state_path, logger--from jiuwenswarm.common.utils import get_agent_workspace_dir+from jiuwenswarm.common.utils import (+ get_agent_workspace_dir,+ get_runtime_state_path,+ get_user_workspace_dir,+ logger,+)_LANGUAGE_NAMES = {"cn": "Chinese", "zh": "Chinese", "en": "English"}@@ -479,92 +482,231 @@ class RuntimePromptRail(DeepAgentRail):if self._channel in ("tui", "web"):# Trusted directories policy for TUI and Web modetrusted_dirs = self._existing_dirs(self._trusted_dirs)- current_dir = (+ agent_workspace_dir = str(get_agent_workspace_dir())+ config_dir = str(get_user_workspace_dir() / "config")+ project_dir = self._existing_dir(self._project_dir)+ runtime_cwd = (self._existing_dir(self._cwd)- or self._existing_dir(self._project_dir)- or (trusted_dirs[0] if trusted_dirs else None)+ or project_dir+ or agent_workspace_dir)- if current_dir:- workspace_dir = str(get_agent_workspace_dir())- project_dir = current_dir- other_dirs = [- path for path in trusted_dirs- if not self._same_path(path, project_dir)- ]- cn_dirs_display = ", ".join(other_dirs) if other_dirs else "无"- en_dirs_display = ", ".join(other_dirs) if other_dirs else "none"- if not self._force_english and self._language == "cn":+ has_project = project_dir is not None+ cwd_is_agent_workspace = self._same_path(runtime_cwd, agent_workspace_dir)+ workspace_boundary = project_dir or runtime_cwd+ other_dirs = []+ for path in trusted_dirs:+ if self._same_path(path, workspace_boundary):+ continue+ if self._same_path(path, runtime_cwd):+ continue+ other_dirs.append(path)+ cn_dirs_display = ", ".join(other_dirs) if other_dirs else "无"+ en_dirs_display = ", ".join(other_dirs) if other_dirs else "none"++ if not self._force_english and self._language == "cn":+ if has_project:current_project_policy = (- "# 当前项目工作空间\n\n"- f"- 当前项目目录:{project_dir}\n"- f"- 系统目录:{workspace_dir}\n\n"- "- 当用户询问“当前工作空间”“当前工作目录”“当前项目目录”“项目空间”或 workspace,"- "且没有明确限定 team workspace、系统目录或其他目录时,直接回答当前项目目录。\n"- "- 不要为了回答这类问题调用 `pwd`、`ls` 或读取内部 Team Leader workspace;"- "也不要把系统目录、team-workspace 或 Team Leader workspace 称为当前工作空间。\n"+ "# 运行时目录上下文\n\n"+ f"- 当前项目目录(项目根目录,也是本次任务的 workspace 边界):{project_dir}\n"+ f"- 当前工作目录(cwd,也是 Bash 默认执行目录):{runtime_cwd}\n"+ f"- Agent 内部数据目录:{agent_workspace_dir}\n"+ f"- JiuwenSwarm 启动配置目录:{config_dir}\n\n"+ "目录含义:\n"+ "- 当前项目目录是用户正在处理的项目根目录,也是本次任务文件操作的主要边界。\n"+ "- 当前工作目录是 Bash 未显式传入 `workdir` 时的默认执行目录,也是相对路径的解析基准。\n"+ "- 当前工作目录可以等于项目目录,也可以是项目目录中的子目录。\n"+ "- Agent 内部数据目录只保存身份、记忆、技能、待办和运行状态,不属于用户项目。\n"+ "- JiuwenSwarm 启动配置目录只保存 JiuwenSwarm 自身配置,不属于用户项目中的 `config/`。\n\n"+ "回答规则:\n"+ "- 用户询问“当前项目”“项目目录”“项目工作空间”或未加限定的 workspace 时,回答当前项目目录。\n"+ "- 用户询问“当前工作目录”“cwd”或“Bash 在哪里执行”时,回答当前工作目录。\n"+ "- 用户询问“Agent 工作空间”“Agent 数据目录”时,回答 Agent 内部数据目录。\n"+ "- 用户询问“JiuwenSwarm 配置目录”时,回答 JiuwenSwarm 启动配置目录。\n")trusted_dirs_content = ("# 工作目录策略\n\n"- f"- 系统目录(不要在其中查找或运行项目文件):{workspace_dir}\n"- f"- 当前项目目录(你正在工作的项目,查询文件、运行测试、执行命令等均应在此目录下进行):{project_dir}\n"+ f"- 当前项目目录:{project_dir}\n"+ f"- 当前工作目录:{runtime_cwd}\n"f"- 其他可访问目录(可读写其中的资源,但不是当前项目目录):{cn_dirs_display}\n\n""重要规则:\n"- "- 命令执行工具(mcp_exec_command)默认的工作目录是系统目录,"- "如果你要在项目目录下执行命令,必须将工具的 workdir 参数设置为当前项目目录,"- f"即 workdir=\"{project_dir}\",不要使用默认值或 cd 方式切换,"- "因为 cd 只在子shell中生效,不会改变工具本身的工作目录\n"- "- 查找项目文件、读取项目代码时,应在当前项目目录下搜索,不要在系统目录下查找\n"- "- 不要在系统目录下运行项目测试或构建,系统目录仅用于存放配置和状态文件\n"- "- 若用户请求的操作涉及超出上述目录范围的路径,必须先向用户确认是否允许此次操作\n"- "- 确认时需明确告知:操作的完整路径、操作类型(读取/编辑/执行)、潜在风险\n"+ "- 项目文件搜索、代码读取与编辑、测试、构建和 Git 操作应限制在当前项目目录内。\n"+ "- 用户任务中的相对路径相对于当前工作目录解析。\n"+ "- Bash 工具未显式传入 `workdir` 时,默认在当前工作目录中执行。\n"+ "- Bash 工具显式传入 `workdir` 时,本次命令在指定目录中执行。\n"+ "- 不要依赖一次 Bash 调用中的 `cd` 改变后续工具调用的工作目录。\n"+ "- 不要在 Agent 内部数据目录中搜索、运行或修改用户项目文件。\n"+ "- 不要将项目中的 `config/` 自动解释为 JiuwenSwarm 启动配置目录。\n"+ "- 若操作涉及当前项目目录和其他已授权目录之外的路径,应先向用户确认。\n"+ )+ elif cwd_is_agent_workspace:+ current_project_policy = (+ "# 运行时目录上下文\n\n"+ "- 当前项目目录:未设置\n"+ f"- 当前工作目录(cwd,也是 Bash 默认执行目录):{runtime_cwd}\n"+ f"- Agent 内部数据目录:{agent_workspace_dir}\n"+ f"- JiuwenSwarm 启动配置目录:{config_dir}\n\n"+ "当前没有绑定用户项目,也没有传入独立的任务工作路径。"+ "当前工作目录暂时回退到 Agent 内部数据目录。\n\n"+ "重要规则:\n"+ "- 当前目录虽然是 Bash 默认执行目录,但它仍然是 Agent 内部数据目录,不是用户项目。\n"+ "- 不要假设其中存在项目代码、Git 仓库或用户项目配置。\n"+ "- 可以在其中执行普通聊天、记忆、待办和非项目型文件任务。\n"+ "- 用户要求搜索、编辑、测试或构建项目时,应先获得明确的项目路径。\n"+ "- 任务中出现 `config/` 时,不要自动将其解释为 JiuwenSwarm 启动配置目录。\n"+ )+ trusted_dirs_content = (+ "# 工作目录策略\n\n"+ f"- 当前工作目录:{runtime_cwd}\n"+ f"- 其他可访问目录:{cn_dirs_display}\n\n"+ "重要规则:\n"+ "- 当前没有项目目录,不要把当前工作目录称为项目目录。\n"+ "- Bash 工具未显式传入 `workdir` 时,默认在当前工作目录中执行。\n"+ "- 用户任务中的相对路径相对于当前工作目录解析。\n"+ "- 用户要求处理项目时,应先获得明确的项目路径。\n")else:current_project_policy = (- "# Current Project Workspace\n\n"+ "# 运行时目录上下文\n\n"+ "- 当前项目目录:未设置\n"+ f"- 当前工作目录(cwd,也是 Bash 默认执行目录):{runtime_cwd}\n"+ f"- Agent 内部数据目录:{agent_workspace_dir}\n"+ f"- JiuwenSwarm 启动配置目录:{config_dir}\n\n"+ "当前没有绑定用户项目。\n\n"+ "目录含义:\n"+ "- 当前工作目录是本次任务的文件操作目录和相对路径解析基准,但不要称其为项目目录。\n"+ "- Bash 未显式传入 `workdir` 时,默认在当前工作目录中执行。\n"+ "- 不要假设当前工作目录是 Git 仓库或代码项目。\n"+ "- Agent 内部数据目录只保存 Agent 自身数据。\n"+ "- 用户要求处理某个项目时,应先获得明确的项目路径。\n"+ "- 任务中出现 `config/` 时,不要自动将其解释为 JiuwenSwarm 启动配置目录。\n"+ )+ trusted_dirs_content = (+ "# 工作目录策略\n\n"+ f"- 当前工作目录:{runtime_cwd}\n"+ f"- 其他可访问目录:{cn_dirs_display}\n\n"+ "重要规则:\n"+ "- 当前工作目录是本次任务的主要文件操作范围,但不是项目目录。\n"+ "- Bash 工具未显式传入 `workdir` 时,默认在当前工作目录中执行。\n"+ "- 用户任务中的相对路径相对于当前工作目录解析。\n"+ "- 用户要求处理项目时,应先获得明确的项目路径。\n"+ )+ else:+ if has_project:+ current_project_policy = (+ "# Runtime Directory Context\n\n"+ f"- Current project directory (project root and workspace boundary): {project_dir}\n"+ f"- Current working directory (cwd and Bash default directory): {runtime_cwd}\n"+ f"- Agent internal data directory: {agent_workspace_dir}\n"+ f"- JiuwenSwarm startup configuration directory: {config_dir}\n\n"+ "Directory semantics:\n"+ "- The current project directory is the user project's root "+ "and the main file-operation boundary.\n"+ "- The current working directory is Bash's default directory when `workdir` is omitted "+ "and the base for relative paths.\n"+ "- The current working directory may equal the project root or be a subdirectory inside it.\n"+ "- The Agent internal data directory stores identity, memory, skills, todos, "+ "and runtime state; it is not part of the user project.\n"+ "- The JiuwenSwarm startup configuration directory stores JiuwenSwarm's own "+ "configuration; it is not the project's `config/` directory.\n\n"+ "Answering rules:\n"+ "- For the current project, project directory, project workspace, or an unqualified "+ "workspace, answer with the current project directory.\n"+ "- For the current working directory, cwd, or Bash execution directory, "+ "answer with the current working directory.\n"+ "- For the Agent workspace or Agent data directory, "+ "answer with the Agent internal data directory.\n"+ "- For the JiuwenSwarm configuration directory, "+ "answer with the JiuwenSwarm startup configuration directory.\n"+ )+ trusted_dirs_content = (+ "# Working Directory Policy\n\n"f"- Current project directory: {project_dir}\n"- f"- System directory: {workspace_dir}\n\n"- "- When the user asks for the current workspace, current working directory, "- "current project directory, project space, or workspace without explicitly "- "saying team workspace, "- "system directory, or another directory, answer directly with the current "- "project directory.\n"- "- Do not call `pwd`, `ls`, or inspect the internal Team Leader workspace "- "to answer this question, and do not call the system directory, "- "team-workspace, or Team Leader workspace the current workspace.\n"+ f"- Current working directory: {runtime_cwd}\n"+ f"- Other accessible directories: {en_dirs_display}\n\n"+ "Important rules:\n"+ "- Project searches, code reads and edits, tests, builds, and Git operations "+ "must stay within the current project directory.\n"+ "- Relative paths in user tasks are resolved against the current working directory.\n"+ "- Bash runs in the current working directory when `workdir` is omitted.\n"+ "- When Bash is given an explicit `workdir`, that directory applies to that command.\n"+ "- Do not rely on `cd` in one Bash call to change the working directory of later tool calls.\n"+ "- Do not search for, run, or modify user project files in the Agent internal data directory.\n"+ "- Do not map the project's relative `config/` path to the JiuwenSwarm startup "+ "configuration directory.\n"+ "- Ask the user before operating outside the current project "+ "and other authorized directories.\n"+ )+ elif cwd_is_agent_workspace:+ current_project_policy = (+ "# Runtime Directory Context\n\n"+ "- Current project directory: not set\n"+ f"- Current working directory (cwd and Bash default directory): {runtime_cwd}\n"+ f"- Agent internal data directory: {agent_workspace_dir}\n"+ f"- JiuwenSwarm startup configuration directory: {config_dir}\n\n"+ "No user project or independent task path is currently bound. "+ "The current working directory has temporarily fallen back to "+ "the Agent internal data directory.\n\n"+ "Important rules:\n"+ "- Although this is Bash's default directory, it remains the Agent internal data directory "+ "and is not a user project.\n"+ "- Do not assume that it contains project code, a Git repository, "+ "or user project configuration.\n"+ "- Ordinary conversation, memory, todo, and non-project file tasks may be performed here.\n"+ "- Obtain an explicit project path before searching, editing, testing, or building a project.\n"+ "- Do not map a task's relative `config/` path to the JiuwenSwarm startup "+ "configuration directory.\n"+ )+ trusted_dirs_content = (+ "# Working Directory Policy\n\n"+ f"- Current working directory: {runtime_cwd}\n"+ f"- Other accessible directories: {en_dirs_display}\n\n"+ "Important rules:\n"+ "- No project directory is set; do not call the current working directory "+ "a project directory.\n"+ "- Bash runs in the current working directory when `workdir` is omitted.\n"+ "- Relative paths in user tasks are resolved against the current working directory.\n"+ "- Obtain an explicit project path before performing project work.\n"+ )+ else:+ current_project_policy = (+ "# Runtime Directory Context\n\n"+ "- Current project directory: not set\n"+ f"- Current working directory (cwd and Bash default directory): {runtime_cwd}\n"+ f"- Agent internal data directory: {agent_workspace_dir}\n"+ f"- JiuwenSwarm startup configuration directory: {config_dir}\n\n"+ "No user project is currently bound.\n\n"+ "Directory semantics:\n"+ "- The current working directory is this task's file-operation directory "+ "and relative-path base, but it is not a project directory.\n"+ "- Bash runs in the current working directory when `workdir` is omitted.\n"+ "- Do not assume that the current working directory is a Git repository or code project.\n"+ "- The Agent internal data directory stores only the Agent's own data.\n"+ "- Obtain an explicit project path before performing project work.\n"+ "- Do not map a task's relative `config/` path to the JiuwenSwarm startup "+ "configuration directory.\n")trusted_dirs_content = ("# Working Directory Policy\n\n"- f"- System directory (never search or run project files here): {workspace_dir}\n"- f"- Current project directory (the project you are working on; "- f"all file queries, test runs, command execution should happen here): {project_dir}\n"- f"- Other accessible directories (read/write allowed, but not the current project): "- f"{en_dirs_display}\n\n"+ f"- Current working directory: {runtime_cwd}\n"+ f"- Other accessible directories: {en_dirs_display}\n\n""Important rules:\n"- "- The command execution tool (mcp_exec_command) defaults its working directory "- "to the system directory. When you need to execute commands in the project directory, "- "you MUST set the tool's workdir parameter to the current project directory, "- f"i.e. workdir=\"{project_dir}\". Do NOT rely on cd to switch directories, "- "because cd only takes effect inside a subshell and does not change the tool's "- "actual working directory\n"- "- When searching for project files or reading project code, search within the "- "current project directory, not the system directory\n"- "- Never run project tests or builds in the system directory; "- "the system directory is only for config and state files\n"- "- If the user requests an operation involving paths outside the above directories, "- "you must first ask the user to confirm whether to allow this operation\n"- "- When confirming, clearly state: the full path, operation type (read/edit/execute), "- "potential risks\n"+ "- The current working directory is this task's main file-operation scope, "+ "but it is not a project directory.\n"+ "- Bash runs in the current working directory when `workdir` is omitted.\n"+ "- Relative paths in user tasks are resolved against the current working directory.\n"+ "- Obtain an explicit project path before performing project work.\n")- self.system_prompt_builder.add_section(PromptSection(- name="tui_current_project_policy",- content={"cn": current_project_policy, "en": current_project_policy},- priority=99,- ))- self.system_prompt_builder.add_section(PromptSection(- name="trusted_dirs_policy",- content={"cn": trusted_dirs_content, "en": trusted_dirs_content},- priority=90,- ))++ self.system_prompt_builder.add_section(PromptSection(+ name="tui_current_project_policy",+ content={"cn": current_project_policy, "en": current_project_policy},+ priority=99,+ ))+ self.system_prompt_builder.add_section(PromptSection(+ name="trusted_dirs_policy",+ content={"cn": trusted_dirs_content, "en": trusted_dirs_content},+ priority=90,+ ))async def _upsert_prompt_attachment(self,diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.pyindex 227f44a369..7918f2ce5f 100644--- a/jiuwenswarm/common/utils.py+++ b/jiuwenswarm/common/utils.py@@ -1101,6 +1101,7 @@ def prepare_workspace(# ----- DeepAgent workspace (standard DeepAgents schema) -----deepagent_workspace = agent_root / "workspace"+ default_project_workspace = deepagent_workspace / "projects"agent_skills = deepagent_workspace / "skills"agent_memory = deepagent_workspace / "memory"@@ -1205,6 +1206,7 @@ def prepare_workspace(# sessions is runtime-only (template may not include it)agent_sessions.mkdir(parents=True, exist_ok=True)+ default_project_workspace.mkdir(parents=True, exist_ok=True)from jiuwenswarm.common.config import migrate_config_from_template, set_preferred_language_in_config_file@@ -1436,6 +1438,40 @@ def get_agent_workspace_dir() -> Path:return get_agent_root_dir() / "workspace"+def get_default_project_workspace_dir() -> Path:+ """Get the fallback task workspace used when no project is bound.++ Agent-owned data such as memory, skills, todo, and sessions stays directly+ under ``get_agent_workspace_dir()``. This directory is only the default cwd+ / workspace boundary for user task artifacts when no project is selected.+ """+ return get_agent_workspace_dir() / "projects"+++def get_default_project_session_workspace_dir(session_id: str | None = None) -> Path:+ """Get the no-project task workspace for a single conversation session.++ Layout:+ <agent-workspace>/projects/<session_id>++ ``session_id`` is used when available so the same conversation keeps a stable+ workspace. If it is missing during early adapter initialization, the shared+ projects root is returned so no throwaway session directory is created.+ """+ base = get_default_project_workspace_dir()+ raw_session = str(session_id or "").strip()+ if not raw_session:+ base.mkdir(parents=True, exist_ok=True)+ return base+ safe_session = re.sub(r"[^A-Za-z0-9_.-]+", "_", raw_session).strip("._-")+ if not safe_session:+ base.mkdir(parents=True, exist_ok=True)+ return base+ workspace = base / safe_session+ workspace.mkdir(parents=True, exist_ok=True)+ return workspace++def get_prompt_attachment_dir() -> Path:"""Get the jiuwenswarm prompt attachment directory path."""diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 78be4565df..13d14e7d2b 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -75,7 +75,10 @@ from jiuwenswarm.common.coding_memory_paths import (from jiuwenswarm.server.runtime.agent_adapter.code_agent_rail import CodeAgentRailfrom jiuwenswarm.common.hooks_config import load_hooks_configfrom jiuwenswarm.server.hooks.user_hook_rail import UserHookRail-from jiuwenswarm.common.utils import get_agent_workspace_dir+from jiuwenswarm.common.utils import (+ get_agent_workspace_dir,+ get_default_project_session_workspace_dir,+)logger = logging.getLogger(__name__)@@ -542,19 +545,21 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):for tool in getattr(rail, 'tools', []) or []:if hasattr(tool, '_workspace_path'):setattr(tool, '_workspace_path', self._agent_workspace_dir)- initial_workspace = self._project_dir or self._workspace_dir+ initial_workspace = self._project_dir or str(+ get_default_project_session_workspace_dir()+ )self._seed_runtime_cwd(initial_workspace, workspace=initial_workspace)setattr(self._instance, "_jiuwenswarm_adapter_mode", "code")setattr(self._instance,"_jiuwenswarm_code_project_dir",- self._project_dir or self._workspace_dir,+ initial_workspace,)setattr(self._instance,"_jiuwenswarm_project_dir",- self._project_dir or self._workspace_dir,+ initial_workspace,)# code 模式不传: vision_model_config, audio_model_config,@@ -1195,17 +1200,13 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):raise RuntimeError("JiuwenSwarmCodeAdapter 未初始化,请先调用 create_instance()")project_workspace = (- runtime_config.project_dir- or self._project_dir- or self._workspace_dir- )- self._seed_runtime_cwd(- runtime_config.cwd+ runtime_config.workspaceor runtime_config.project_diror self._project_dir- or self._workspace_dir,- workspace=project_workspace,+ or str(get_default_project_session_workspace_dir(runtime_config.session_id)))+ task_cwd = runtime_config.cwd or project_workspace+ self._seed_runtime_cwd(task_cwd, workspace=project_workspace)resolved_language = self._resolve_runtime_language()resolved_channel = str(runtime_config.channel_id orself._resolve_prompt_channel(runtime_config.session_id) or "web").strip() or "web"@@ -1217,7 +1218,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):self._runtime_prompt_rail.set_mode(runtime_config.mode)self._runtime_prompt_rail.set_trusted_dirs(runtime_config.trusted_dirs)self._runtime_prompt_rail.set_runtime_paths(- cwd=runtime_config.cwd,+ cwd=task_cwd,project_dir=runtime_config.project_dir or self._project_dir,)self._runtime_prompt_rail.set_session_id(runtime_config.session_id)@@ -1239,7 +1240,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):channel=resolved_channel,session_id=runtime_config.session_id,project_dir=runtime_config.project_dir- or runtime_config.cwd+ or task_cwdor self._project_diror self._workspace_dir,)diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex bca457f504..d2c40326fc 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -290,6 +290,7 @@ from jiuwenswarm.common.utils import (get_agent_skills_dir,get_agent_workspace_dir,get_checkpoint_dir,+ get_default_project_session_workspace_dir,get_env_file,get_prompt_attachment_dir,get_runtime_state_path,@@ -4403,8 +4404,11 @@ class JiuWenSwarmDeepAdapter:)await self._instance.ensure_initialized()- self._seed_runtime_cwd(self._project_dir or self._workspace_dir)- setattr(self._instance, "_jiuwenswarm_project_dir", self._project_dir or self._workspace_dir)+ initial_runtime_workspace = self._project_dir or str(+ get_default_project_session_workspace_dir()+ )+ self._seed_runtime_cwd(initial_runtime_workspace, workspace=initial_runtime_workspace)+ setattr(self._instance, "_jiuwenswarm_project_dir", initial_runtime_workspace)self._sync_a2x_runtime_state()self._registered_mcp_server_ids.clear()@@ -5082,13 +5086,14 @@ class JiuWenSwarmDeepAdapter:if self._instance is None:raise RuntimeError("JiuWenSwarmDeepAdapter 未初始化,请先调用 create_instance()")- self._seed_runtime_cwd(- runtime_config.cwd+ task_workspace = (+ runtime_config.workspaceor runtime_config.project_diror self._project_dir- or self._workspace_dir,- workspace=runtime_config.workspace,+ or str(get_default_project_session_workspace_dir(runtime_config.session_id)))+ task_cwd = runtime_config.cwd or task_workspace+ self._seed_runtime_cwd(task_cwd, workspace=task_workspace)resolved_language = self._resolve_runtime_language()resolved_channel = (str(@@ -5103,7 +5108,7 @@ class JiuWenSwarmDeepAdapter:self._runtime_prompt_rail.set_channel(resolved_channel)self._runtime_prompt_rail.set_trusted_dirs(runtime_config.trusted_dirs)self._runtime_prompt_rail.set_runtime_paths(- cwd=runtime_config.cwd,+ cwd=task_cwd,project_dir=runtime_config.project_dir or self._project_dir,)self._runtime_prompt_rail.set_model_name(self._resolve_model_name())@@ -5132,9 +5137,9 @@ class JiuWenSwarmDeepAdapter:channel=resolved_channel,session_id=runtime_config.session_id,project_dir=runtime_config.project_dir- or runtime_config.cwd+ or task_cwdor self._project_dir- or self._workspace_dir,+ or str(get_default_project_session_workspace_dir(runtime_config.session_id)),)await self._update_rails_for_mode(runtime_config.mode)diff --git a/tests/system_tests/conftest.py b/tests/system_tests/conftest.pyindex e806e1011f..ec0caa8d5c 100644--- a/tests/system_tests/conftest.py+++ b/tests/system_tests/conftest.py@@ -169,6 +169,7 @@ def verify_workspace_structure():workspace_dir / "agent" / "memory",workspace_dir / "agent" / "sessions",workspace_dir / "agent" / "workspace",+ workspace_dir / "agent" / "workspace" / "projects",workspace_dir / "agent" / ".checkpoint",workspace_dir / "agent" / ".logs",]diff --git a/tests/unit_tests/a2ui/test_auto_harness_channel_context.py b/tests/unit_tests/a2ui/test_auto_harness_channel_context.pyindex 9e38094982..4e3d6d9b73 100644--- a/tests/unit_tests/a2ui/test_auto_harness_channel_context.py+++ b/tests/unit_tests/a2ui/test_auto_harness_channel_context.py@@ -94,8 +94,8 @@ def test_prompt_channel_resolver_keeps_tui_prefix_non_web():@pytest.mark.asyncio-async def test_runtime_config_syncs_channel_to_response_prompt_rail(monkeypatch):- """Inner ReAct model-call rails need the adapter-resolved channel."""+async def test_runtime_config_syncs_channel_and_task_workspace(monkeypatch):+ """Runtime config must sync the channel and task paths into inner rails."""adapter = object.__new__(JiuWenSwarmDeepAdapter)adapter._instance = object()adapter._is_session_scoped_adapter = True@@ -120,7 +120,10 @@ async def test_runtime_config_syncs_channel_to_response_prompt_rail(monkeypatch)monkeypatch.setattr(JiuWenSwarmDeepAdapter,"_seed_runtime_cwd",- lambda self, cwd=None, workspace=None: None,+ lambda self, cwd=None, workspace=None: captured.update(+ cwd=cwd,+ workspace=workspace,+ ),)monkeypatch.setattr(JiuWenSwarmDeepAdapter, "_resolve_runtime_language", lambda self: "cn")monkeypatch.setattr(JiuWenSwarmDeepAdapter, "_write_runtime_state", lambda self, **kwargs: None)@@ -143,7 +146,29 @@ async def test_runtime_config_syncs_channel_to_response_prompt_rail(monkeypatch)session_id="sess_123",mode="agent.fast",channel_id="web",+ cwd="/task/project/backend",+ workspace="/task/project",+ project_dir="/different/project",))- assert captured == {"channel": "web"}+ assert captured == {+ "channel": "web",+ "cwd": "/task/project/backend",+ "workspace": "/task/project",+ }++ await adapter._update_runtime_config(+ JiuWenSwarmDeepAdapter._RuntimeConfig(+ session_id="sess_123",+ mode="agent.fast",+ channel_id="web",+ project_dir="/task/second-project",+ )+ )++ assert captured == {+ "channel": "web",+ "cwd": "/task/second-project",+ "workspace": "/task/second-project",+ }diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pyindex 4d3d21f2dc..05c4481a95 100644--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -104,7 +104,7 @@ class _FakeRuntimeInstance:def test_build_agent_identity_prompt_contains_identity_section_only():prompt = build_agent_identity_prompt(language="zh")- assert "# 你的家" in prompt+ assert "# JiuwenSwarm 内部数据" in promptassert "## Symphony Orchestration" not in promptassert "`symphony_compose_score`" not in promptassert "# 消息说明" not in prompt@@ -407,15 +407,25 @@ async def test_runtime_git_status_attachment_clears_when_git_context_disappears(@pytest.mark.asyncio-async def test_runtime_prompt_uses_runtime_cwd_over_stale_trusted_dir(tmp_path):+async def test_runtime_prompt_uses_runtime_cwd_over_stale_trusted_dir(tmp_path, monkeypatch):builder = SystemPromptBuilder(language="en")agent = _FakeAgent(builder)stale_dir = tmp_path / "missing-worktree"project_dir = tmp_path / "project"current_dir = project_dir / "current"extra_dir = tmp_path / "extra"+ agent_data_dir = tmp_path / "agent-data"current_dir.mkdir(parents=True)extra_dir.mkdir()+ agent_data_dir.mkdir()+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail.get_agent_workspace_dir",+ lambda: agent_data_dir,+ )+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail.get_user_workspace_dir",+ lambda: tmp_path / "jiuwenswarm-data",+ )runtime_rail = RuntimePromptRail(language="en", channel="tui")runtime_rail.init(agent)@@ -431,18 +441,92 @@ async def test_runtime_prompt_uses_runtime_cwd_over_stale_trusted_dir(tmp_path):await runtime_rail.before_model_call(ctx)prompt = builder.build()- assert "# Current Project Workspace" in prompt- assert "Current project directory" in prompt- assert "Do not call `pwd`, `ls`" in prompt+ assert "# Runtime Directory Context" in prompt+ assert "Current project directory (project root and workspace boundary)" in prompt+ assert "Current working directory (cwd and Bash default directory)" in prompt+ assert "Agent internal data directory" in promptassert "# Working Directory Policy" in prompt+ assert str(project_dir) in promptassert str(current_dir) in promptassert str(stale_dir) not in promptassert str(extra_dir) in prompt+ assert "System directory" not in promptitems = await agent.prompt_attachment_manager.list_by_filter(session_id="sess1")assert [item.id for item in items if item.id.endswith(".trusted_dirs_policy")] == []+async def test_runtime_prompt_describes_external_cwd_without_project(tmp_path, monkeypatch):+ builder = SystemPromptBuilder(language="en")+ agent = _FakeAgent(builder)+ agent_data_dir = tmp_path / "agent-data"+ task_dir = tmp_path / "standalone-task"+ agent_data_dir.mkdir()+ task_dir.mkdir()+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail.get_agent_workspace_dir",+ lambda: agent_data_dir,+ )+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail.get_user_workspace_dir",+ lambda: tmp_path / "jiuwenswarm-data",+ )++ runtime_rail = RuntimePromptRail(language="en", channel="web")+ runtime_rail.init(agent)+ runtime_rail.set_runtime_paths(cwd=str(task_dir), project_dir=None)+ ctx = AgentCallbackContext(+ agent=agent,+ inputs=None,+ session=_FakeSession(),+ extra={},+ )++ await runtime_rail.before_model_call(ctx)++ prompt = builder.build()+ assert "Current project directory: not set" in prompt+ assert str(task_dir) in prompt+ assert "No user project is currently bound" in prompt+ assert "it is not a project directory" in prompt+ assert "fallen back to the Agent internal data directory" not in prompt+++async def test_runtime_prompt_describes_agent_data_cwd_fallback(tmp_path, monkeypatch):+ builder = SystemPromptBuilder(language="cn")+ agent = _FakeAgent(builder)+ agent_data_dir = tmp_path / "agent-data"+ agent_data_dir.mkdir()+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail.get_agent_workspace_dir",+ lambda: agent_data_dir,+ )+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail.get_user_workspace_dir",+ lambda: tmp_path / "jiuwenswarm-data",+ )++ runtime_rail = RuntimePromptRail(language="cn", channel="web")+ runtime_rail.init(agent)+ runtime_rail.set_runtime_paths(cwd=None, project_dir=None)+ ctx = AgentCallbackContext(+ agent=agent,+ inputs=None,+ session=_FakeSession(),+ extra={},+ )++ await runtime_rail.before_model_call(ctx)++ prompt = builder.build()+ assert "当前项目目录:未设置" in prompt+ assert str(agent_data_dir) in prompt+ assert "当前工作目录暂时回退到 Agent 内部数据目录" in prompt+ assert "它仍然是 Agent 内部数据目录,不是用户项目" in prompt++@pytest.mark.asyncioasync def test_runtime_prompt_language_output_prefers_rail_language_over_runtime_state(monkeypatch,diff --git a/tests/unit_tests/test_utils.py b/tests/unit_tests/test_utils.pyindex a6c5433503..9d0950ed80 100644--- a/tests/unit_tests/test_utils.py+++ b/tests/unit_tests/test_utils.py@@ -49,6 +49,32 @@ class TestPathResolution:assert isinstance(agent_workspace, Path)assert "agent" in str(agent_workspace)+ @staticmethod+ def test_get_default_project_workspace_dir():+ """Test no-project task workspace lives under agent workspace/projects."""+ project_workspace = utils.get_default_project_workspace_dir()+ assert isinstance(project_workspace, Path)+ assert project_workspace == utils.get_agent_workspace_dir() / "projects"++ @staticmethod+ def test_get_default_project_session_workspace_dir():+ """Test no-project task workspace is scoped by session."""+ session_workspace = utils.get_default_project_session_workspace_dir("abc-123")+ assert isinstance(session_workspace, Path)+ assert session_workspace == (+ utils.get_default_project_workspace_dir()+ / "abc-123"+ )+ assert session_workspace.exists()++ @staticmethod+ def test_get_default_project_session_workspace_dir_without_session():+ """Test early initialization does not create a throwaway session folder."""+ session_workspace = utils.get_default_project_session_workspace_dir()+ assert isinstance(session_workspace, Path)+ assert session_workspace == utils.get_default_project_workspace_dir()+ assert session_workspace.exists()+@staticmethoddef test_path_caching():"""Test that path results are cached."""