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
refactor(workspace): workspace 改名为 jiuwenclaw_workspace
huangyuzhebd240bed5e96
diff --git a/docs/en/Heartbeat.md b/docs/en/Heartbeat.mdindex a336067488..b2b8525291 100644--- a/docs/en/Heartbeat.md+++ b/docs/en/Heartbeat.md@@ -142,7 +142,7 @@ A: Set `heartbeat.active_hours.start` / `end`, e.g., `start: 09:00`, `end: 18:00A: Set the `HEARTBEAT_TIMEOUT` environment variable (seconds). On timeout, the beat is marked failed and a WARNING is logged.**Q: Where must `HEARTBEAT.md` live?**-A: At the DeepAgent workspace root: `~/.jiuwenswarm/agent/workspace/HEARTBEAT.md`. Otherwise, it is treated as "no custom tasks" and only `HEARTBEAT_OK` is returned.+A: At the DeepAgent workspace root: `~/.jiuwenswarm/agent/jiuwenclaw_workspace/HEARTBEAT.md`. Otherwise, it is treated as "no custom tasks" and only `HEARTBEAT_OK` is returned.---diff --git a/docs/en/InstallGuide.md b/docs/en/InstallGuide.mdindex e55fc78728..ed756fe88d 100644--- a/docs/en/InstallGuide.md+++ b/docs/en/InstallGuide.md@@ -390,7 +390,7 @@ rsync -av ~/.jiuwenswarm ~/.jiuwenswarm_backup| `agent/memory/` | User memory data || `agent/home/` | Identity and task data || `agent/skills/` | Skills library (custom skills and config) |-| `agent/workspace/` | Workspace files |+| `agent/jiuwenclaw_workspace/` | Workspace files |#### 2. Perform the upgradediff --git a/docs/en/Quickstart.md b/docs/en/Quickstart.mdindex bc0352b77f..cfde14d365 100644--- a/docs/en/Quickstart.md+++ b/docs/en/Quickstart.md@@ -337,7 +337,7 @@ When you need JiuwenSwarm to forget all conversation history and user informatioMemory files are stored in:- **Windows**: `C:\Users\<your-username>\.jiuwenswarm\agent\workspace\memory\`-- **Linux/Mac**: `~/.jiuwenswarm/agent/workspace/memory/`+- **Linux/Mac**: `~/.jiuwenswarm/agent/jiuwenclaw_workspace/memory/`**Method 1: Delete via Agent**Tell JiuwenSwarm: "Please delete all memory files" or "Clear my memory", Agent will call file tools to delete files in the memory directory.diff --git a/docs/en/Skills.md b/docs/en/Skills.mdindex 76e402c246..51332005b8 100644--- a/docs/en/Skills.md+++ b/docs/en/Skills.md@@ -167,7 +167,7 @@ Best for:Copy skill folder into:```text- C:\Users\<username>\.jiuwenswarm\service_default\agent_default\jiuwenswarm_workspace\skills\+ C:\Users\<username>\.jiuwenswarm\service_default\agent_default\agent\jiuwenclaw_workspace\skills\```4. **Verify**@@ -259,7 +259,7 @@ The agent lists installed skill names, sources, versions, and related info.**Method 3: File path**```text-C:\Users\<username>\.jiuwenswarm\service_default\agent_default\jiuwenswarm_workspace\skills\+C:\Users\<username>\.jiuwenswarm\service_default\agent_default\agent\jiuwenclaw_workspace\skills\```Each subfolder is one skill.diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.mdindex 4084da5148..559f9d9cc5 100644--- a/docs/en/SlashCommands.md+++ b/docs/en/SlashCommands.md@@ -85,7 +85,7 @@ Manages directories AI can access for file read, edit, and execute operations.#### Concepts-- **System default workspace**: Fixed path `~/.jiuwenswarm/agent/jiuwenswarm_workspace`, always available+- **System default workspace**: Fixed path `~/.jiuwenswarm/agent/jiuwenclaw_workspace`, always available- **Trusted directories (`trusted_dirs`)**: User-authorized accessible directories, managed by TUI, passed to backend Agent#### Control Logic@@ -213,7 +213,7 @@ Manages model configs defined under `models.defaults` in `config.yaml`. SupportsPer-turn diffs are computed from `.agent_history/file_ops_jiuwenswarm*.json` logs, not from git. The service reads and merges file operation logs from multiple locations:-1. Agent workspace (`~/.jiuwenswarm/agent/jiuwenswarm_workspace/.agent_history/`)+1. Agent workspace (`~/.jiuwenswarm/agent/jiuwenclaw_workspace/.agent_history/`)2. User workspace `.agent_history/`3. Project directory `.agent_history/` (session-specific and global files)@@ -515,7 +515,7 @@ Manage skills lifecycle: listing, installing, uninstalling, marketplace source m- **Marketplace source**: A remote Git repository that hosts available skills. Each source has a name, URL, and enabled/disabled state.- **Spec**: The install identifier format supporting: `<skill>@builtin` (builtin), `<slug>@clawhub` (ClawHub), `<skill>@<marketplace>` (Git marketplace); bare names without `@` are auto-detected as builtin if applicable.- **Local install**: Use `/skills install <path>` to install from a local directory (must contain `SKILL.md`) or remote archive URL; paths/URLs are auto-detected and routed to the local import flow.-- **Install location**: The directory where a skill is stored after installation (`~/.jiuwenswarm/agent/jiuwenswarm_workspace/skills/`).+- **Install location**: The directory where a skill is stored after installation (`~/.jiuwenswarm/agent/jiuwenclaw_workspace/skills/`).- **Source tag**: Each skill in the list is tagged with its source: `[builtin]` = builtin, `[local]` = imported, `[clawhub]` = ClawHub, `[skillnet]` = SkillNet, `[project]` or marketplace name = other.#### Grouped List Displaydiff --git a/docs/zh/Quickstart.md b/docs/zh/Quickstart.mdindex 31889e1fb8..d30893c89f 100644--- a/docs/zh/Quickstart.md+++ b/docs/zh/Quickstart.md@@ -342,7 +342,7 @@ cd jiuwenswarm记忆文件存储路径:- **Windows**:`C:\Users\<你的用户名>\.jiuwenswarm\agent\workspace\memory\`-- **Linux/Mac**:`~/.jiuwenswarm/agent/workspace/memory/`+- **Linux/Mac**:`~/.jiuwenswarm/agent/jiuwenclaw_workspace/memory/`**方式一:通过 Agent 删除**直接告诉 JiuwenSwarm:"请删除所有记忆文件" 或 "清空我的记忆",Agent 会调用文件工具删除 memory 目录下的文件。diff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"index 64ba0e32f4..26de864ad1 100644--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"@@ -86,7 +86,7 @@#### 概念说明-- **系统默认工作空间(workspace)**:固定路径 `~/.jiuwenswarm/agent/jiuwenswarm_workspace`,始终可用+- **系统默认工作空间(workspace)**:固定路径 `~/.jiuwenswarm/agent/jiuwenclaw_workspace`,始终可用- **可信目录(trusted_dirs)**:用户授权的可访问目录,由 TUI 管理,传递给后端 Agent#### 控制逻辑@@ -216,7 +216,7 @@按轮次 diff 基于 `.agent_history/file_ops_jiuwenswarm*.json` 日志计算,而非 git。服务从多个位置读取并合并文件操作日志:-1. Agent 工作区(`~/.jiuwenswarm/agent/jiuwenswarm_workspace/.agent_history/`)+1. Agent 工作区(`~/.jiuwenswarm/agent/jiuwenclaw_workspace/.agent_history/`)2. 用户工作区 `.agent_history/`3. 项目目录 `.agent_history/`(含 session 专属文件和全局文件)@@ -535,7 +535,7 @@- **市场源(Marketplace source)**:托管可用技能的远程 Git 仓库,每个源包含名称、URL 和启用/禁用状态。- **规格标识(Spec)**:安装时使用的标识格式,支持以下几种:`<技能名>@builtin`(内置)、`<slug>@clawhub`(ClawHub)、`<技能名>@<市场源名>`(Git 市场源);裸名不带 `@` 时系统会自动检测是否为内置技能。- **本地安装(Local install)**:通过 `/skills install <path>` 将本地目录(需包含 `SKILL.md`)或远程归档 URL 安装为自定义技能;路径/URL 会自动识别并走本地导入流程。-- **安装位置(Install location)**:技能安装后的存储目录(`~/.jiuwenswarm/agent/jiuwenswarm_workspace/skills/`)。+- **安装位置(Install location)**:技能安装后的存储目录(`~/.jiuwenswarm/agent/jiuwenclaw_workspace/skills/`)。- **来源标签(Source tag)**:列表中每项技能标注来源,`[builtin]` 表示内置、`[local]` 表示本地导入、`[clawhub]` 表示从 ClawHub 安装、`[project]` 或市场源名表示其他来源。#### 列表分组展示diff --git "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md" "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"index 0f08e8016d..9dfe818c12 100644--- "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"+++ "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"@@ -216,7 +216,7 @@ jiuwenswarm-tui --session "$(printf 'a%.0s' {1..200})" # 超 128 → 长度超#### `/workspace`(可信目录)-- 系统默认工作空间:`~/.jiuwenswarm/agent/jiuwenswarm_workspace`(始终可用)。+- 系统默认工作空间:`~/.jiuwenswarm/agent/jiuwenclaw_workspace`(始终可用)。- `add`:默认路径为当前工作目录;成功后会 `command.add_dir` 同步到服务端并 `remember: true`。- `set`:重置为单个可信目录;若已有列表会二次确认。- 详见 [Slash命令表.md](Slash命令表.md) 的 `/workspace` 小节。diff --git "a/docs/zh/\345\256\211\350\243\205\346\214\207\345\215\227.md" "b/docs/zh/\345\256\211\350\243\205\346\214\207\345\215\227.md"index c2f6699c2d..478d153bc1 100644--- "a/docs/zh/\345\256\211\350\243\205\346\214\207\345\215\227.md"+++ "b/docs/zh/\345\256\211\350\243\205\346\214\207\345\215\227.md"@@ -392,7 +392,7 @@ rsync -av ~/.jiuwenswarm ~/.jiuwenswarm_backup| `agent/memory/` | 用户记忆数据 || `agent/home/` | 身份与任务信息 || `agent/skills/` | 技能库(自定义技能和配置) |-| `agent/workspace/` | 工作区文件 |+| `agent/jiuwenclaw_workspace/` | 工作区文件 |#### 2. 执行升级diff --git "a/docs/zh/\345\267\245\345\205\267\346\235\203\351\231\220\344\270\216\345\256\211\345\205\250\351\230\262\346\212\244.md" "b/docs/zh/\345\267\245\345\205\267\346\235\203\351\231\220\344\270\216\345\256\211\345\205\250\351\230\262\346\212\244.md"index 80a83b2bc9..0ffebeab96 100644--- "a/docs/zh/\345\267\245\345\205\267\346\235\203\351\231\220\344\270\216\345\256\211\345\205\250\351\230\262\346\212\244.md"+++ "b/docs/zh/\345\267\245\345\205\267\346\235\203\351\231\220\344\270\216\345\256\211\345\205\250\351\230\262\346\212\244.md"@@ -128,7 +128,7 @@ permissions:```- **独立开关**:`file_guard.enabled: false` 时整层路径防护关闭(含旧外部目录检查),不影响 `tools` / `rules`。-- **`workspace`**:按 R/W/X 放行**运行时** `workspace_root`(通常为 `~/.jiuwenswarm/agent/workspace`);拿不到 root 时跳过该规则并打 WARN。Native **无** Legacy 式隐式 workspace 放行,须显式配置本项或 `paths`。+- **`workspace`**:按 R/W/X 放行**运行时** `workspace_root`(通常为 `~/.jiuwenswarm/agent/jiuwenclaw_workspace`);拿不到 root 时跳过该规则并打 WARN。Native **无** Legacy 式隐式 workspace 放行,须显式配置本项或 `paths`。- **`trusted_dirs`**:TUI 项目 cwd / `/add-dir` 热更新目录,由引擎编译为前缀 allow(独立于 `workspace`)。- **R/W/X**:同一路径可分别配置;Write/Exec⇒Read 蕴含,显式 `read: deny` 优先。- **匹配**:`match: prefix`(缺省,最长前缀)或 `glob`。diff --git "a/docs/zh/\345\277\203\350\267\263.md" "b/docs/zh/\345\277\203\350\267\263.md"index 00477694bc..b6a86fbd3e 100644--- "a/docs/zh/\345\277\203\350\267\263.md"+++ "b/docs/zh/\345\277\203\350\267\263.md"@@ -134,7 +134,7 @@ A:在 `heartbeat.active_hours` 中设置 `start` / `end`,例如 `start: 09:0A:可设置环境变量 `HEARTBEAT_TIMEOUT`(秒)。超时后本次心跳记为失败,会在日志中打 WARNING**Q:HEARTBEAT.md 放在哪里?**-A:必须放在 DeepAgent workspace 根目录下:`~/.jiuwenswarm/agent/workspace/HEARTBEAT.md`。否则会被视为「无自定义任务」,仅返回 `HEARTBEAT_OK`。+A:必须放在 DeepAgent workspace 根目录下:`~/.jiuwenswarm/agent/jiuwenclaw_workspace/HEARTBEAT.md`。否则会被视为「无自定义任务」,仅返回 `HEARTBEAT_OK`。---diff --git "a/docs/zh/\346\212\200\350\203\275.md" "b/docs/zh/\346\212\200\350\203\275.md"index 49924762e4..35c44a0e58 100644--- "a/docs/zh/\346\212\200\350\203\275.md"+++ "b/docs/zh/\346\212\200\350\203\275.md"@@ -164,7 +164,7 @@ ClawHub 访问地址:https://clawhub.ai/skills将技能文件夹复制到:```- C:\Users\<用户名>\.jiuwenswarm\service_default\agent_default\jiuwenswarm_workspace\skills\+ C:\Users\<用户名>\.jiuwenswarm\service_default\agent_default\agent\jiuwenclaw_workspace\skills\```4. **确认生效**@@ -258,7 +258,7 @@ ClawHub 访问地址:https://clawhub.ai/skills直接打开文件夹:```-C:\Users\<用户名>\.jiuwenswarm\service_default\agent_default\jiuwenswarm_workspace\skills\+C:\Users\<用户名>\.jiuwenswarm\service_default\agent_default\agent\jiuwenclaw_workspace\skills\```每个子文件夹对应一个技能。diff --git a/jiuwenswarm/agents/harness/common/memory/external_memory_config.py b/jiuwenswarm/agents/harness/common/memory/external_memory_config.pyindex 9b564c9516..ee7dd6dfd1 100644--- a/jiuwenswarm/agents/harness/common/memory/external_memory_config.py+++ b/jiuwenswarm/agents/harness/common/memory/external_memory_config.py@@ -101,16 +101,16 @@ def _nonempty_str(value: Any) -> str | None:def _resolve_tenant_agent_workspace_dir(*, workspace_key: str | None = None) -> Path:- """``workspace_{key}/agent/workspace`` (jiuwenswarm layout)."""+ """``workspace_{key}/agent/jiuwenclaw_workspace`` (jiuwenswarm layout)."""wk = workspace_key if workspace_key is not None else get_bound_workspace_key()wk = normalize_tenant_scope_id(wk)- return get_multi_tenant_user_workspace_dir(wk) / "agent" / "workspace"+ return get_multi_tenant_user_workspace_dir(wk) / "agent" / "jiuwenclaw_workspace"def _resolve_ltm_dir(*, workspace_key: str | None = None) -> Path:"""Default LTM dir under the tenant agent workspace.- Path: ``workspace_{key}/agent/workspace/memory/ltm``+ Path: ``workspace_{key}/agent/jiuwenclaw_workspace/memory/ltm``When ``workspace_key`` is omitted, uses the key bound via:func:`~jiuwenswarm.server.runtime.tenant_context.bind_workspace_key`.diff --git a/jiuwenswarm/agents/harness/common/plugins/rail_manager.py b/jiuwenswarm/agents/harness/common/plugins/rail_manager.pyindex 547f5ae85a..34db73da46 100644--- a/jiuwenswarm/agents/harness/common/plugins/rail_manager.py+++ b/jiuwenswarm/agents/harness/common/plugins/rail_manager.py@@ -93,7 +93,7 @@ class RailManager:import osif is_enterprise():workspace = get_multi_tenant_user_workspace_dir(self.workspace_key)- return workspace / "agent" / "workspace" / "extensions"+ return workspace / "agent" / "jiuwenclaw_workspace" / "extensions"return get_agent_workspace_dir() / "extensions"@propertydiff --git a/jiuwenswarm/agents/harness/common/recommendation/profile_extractor.py b/jiuwenswarm/agents/harness/common/recommendation/profile_extractor.pyindex ddfc8e6d64..59d4718a73 100644--- a/jiuwenswarm/agents/harness/common/recommendation/profile_extractor.py+++ b/jiuwenswarm/agents/harness/common/recommendation/profile_extractor.py@@ -4,7 +4,7 @@只存引擎运行态——冷却记录 + 推荐历史。用户画像已废弃(所有推荐基于当前对话)。-Storage: ``~/.jiuwenswarm/agent/workspace/recommendation.json``+Storage: ``~/.jiuwenswarm/agent/jiuwenclaw_workspace/recommendation.json``"""from __future__ import annotationsdiff --git a/jiuwenswarm/app.py b/jiuwenswarm/app.pyindex 7a85feb1fd..488454319f 100644--- a/jiuwenswarm/app.py+++ b/jiuwenswarm/app.py@@ -32,8 +32,8 @@ _parsed_dotenv_path = get_parsed_dotenv()_workspace_dir = get_user_workspace_dir()_config_file = _workspace_dir / "config" / "config.yaml"-_new_workspace = _workspace_dir / "agent" / "workspace"-_old_workspace = _workspace_dir / "agent" / "jiuwenclaw_workspace"+_new_workspace = _workspace_dir / "agent" / "jiuwenclaw_workspace"+_old_workspace = _workspace_dir / "agent" / "workspace"# 始终清理 Team 旧版本遗留文件(幂等操作,在 prepare_workspace 之前执行)cleanup_team_files(_workspace_dir)diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/workspace-dir.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/workspace-dir.tsindex 6f00e5de0f..e0249c8fc8 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/workspace-dir.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/workspace-dir.ts@@ -81,7 +81,7 @@ function showAllTrustedPaths(ctx: CommandContext): void {// Show system default workspace (fixed)items.push({label: "workspace (system)",- value: "~/.jiuwenswarm/agent/workspace",+ value: "~/.jiuwenswarm/agent/jiuwenclaw_workspace",});// Show current project scope (always resolved absolute path)diff --git a/jiuwenswarm/channels/tui/frontend/src/core/tui-trusted-dirs-store.ts b/jiuwenswarm/channels/tui/frontend/src/core/tui-trusted-dirs-store.tsindex bb6e7cb034..0cc92d4b6c 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/tui-trusted-dirs-store.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/tui-trusted-dirs-store.ts@@ -332,5 +332,5 @@ export function isTrustedDir(path: string): boolean {* Get the default workspace path.*/export function getDefaultWorkspacePath(): string {- return resolve(homedir(), ".jiuwenswarm/agent/workspace");+ return resolve(homedir(), ".jiuwenswarm/agent/jiuwenclaw_workspace");}diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex ddf6546c8e..074d64a33d 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -1871,7 +1871,7 @@ export class AppScreen implements Component, Focusable {{label: "No, use default workspace",value: "no",- description: "Only ~/.jiuwenswarm/agent/workspace will be accessible",+ description: "Only ~/.jiuwenswarm/agent/jiuwenclaw_workspace will be accessible",},];this.startupPromptList = new SelectList(items, 2, selectListTheme, {diff --git a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/index.tsxindex 9e6acdf0ec..670c756b6f 100644--- a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/index.tsx@@ -197,7 +197,7 @@ export function AgentPanel({ sessionId: _sessionId }: AgentPanelProps) {}}- const res = await fetch('/file-api/file-content?path=agent/workspace/agent-data.json');+ const res = await fetch('/file-api/file-content?path=agent/jiuwenclaw_workspace/agent-data.json');if (!res.ok) {throw new Error('FETCH_FAILED');}diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsxindex e4bb08cb7b..27fb6c2173 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx@@ -339,7 +339,7 @@ export function SessionsPanel({const rows = await fetchDirEntries(rootDir, 0);// Check for todo.json in DeepAgent workspace todo directory- const todoPath = `agent/workspace/todo/${sessionId}/todo.json`;+ const todoPath = `agent/jiuwenclaw_workspace/todo/${sessionId}/todo.json`;try {const todoResp = await fetch(`/file-api/file-content?path=${encodeURIComponent(todoPath)}`, { cache: 'no-store' });if (todoResp.ok) {diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex b39bbd7840..4b8ec4d681 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -2176,7 +2176,7 @@"markdownOnly": "Only Markdown/JSON (.md/.mdx/.json) preview is supported","errors": {"refreshFailed": "Refresh failed: unable to rebuild the agent file index. Check the generator script logs.",- "loadFailed": "Unable to read the agent file list. Check whether agent/workspace/agent-data.json has been generated."+ "loadFailed": "Unable to read the agent file list. Check whether agent/jiuwenclaw_workspace/agent-data.json has been generated."}},"fileViewer": {@@ -2500,7 +2500,7 @@"helpTitle": "Usage Guide","help0": "Extension folder must contain rail.py as the entry file","help1": "Rail extension files must inherit from DeepAgentRail or AgentRail base class",- "help2": "Extension files are saved to ~/.jiuwenswarm/agent/workspace/extensions/ directory",+ "help2": "Extension files are saved to ~/.jiuwenswarm/agent/jiuwenclaw_workspace/extensions/ directory","errors": {"missingFolderPath": "Missing folder_path parameter","folderNotFound": "Folder does not exist or is not a directory: {{path}}",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex b214d51f9d..f9acad7b73 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -2163,7 +2163,7 @@"markdownOnly": "仅支持 Markdown/JSON(.md/.mdx/.json)预览","errors": {"refreshFailed": "刷新失败:无法重建 agent 文件索引,请检查生成脚本日志。",- "loadFailed": "无法读取 agent 文件列表,请检查 agent/workspace/agent-data.json 是否已生成。"+ "loadFailed": "无法读取 agent 文件列表,请检查 agent/jiuwenclaw_workspace/agent-data.json 是否已生成。"}},"fileViewer": {@@ -2487,7 +2487,7 @@"helpTitle": "使用说明","help0": "扩展文件夹必须包含 rail.py 作为入口文件","help1": "Rail 扩展文件必须继承 DeepAgentRail 或 AgentRail 基类",- "help2": "扩展文件会被保存到 ~/.jiuwenswarm/agent/workspace/extensions/ 目录",+ "help2": "扩展文件会被保存到 ~/.jiuwenswarm/agent/jiuwenclaw_workspace/extensions/ 目录","errors": {"missingFolderPath": "缺少 folder_path 参数","folderNotFound": "文件夹不存在或不是目录:{{path}}",diff --git a/jiuwenswarm/cli/chat.py b/jiuwenswarm/cli/chat.pyindex af60aa4123..d91483e310 100644--- a/jiuwenswarm/cli/chat.py+++ b/jiuwenswarm/cli/chat.py@@ -53,7 +53,7 @@ logger = logging.getLogger(__name__)# ── Trusted-directory persistence (local, no server/harness changes) ───-# 基于 get_agent_workspace_dir()(~/.jiuwenswarm/agent/workspace),+# 基于 get_agent_workspace_dir()(~/.jiuwenswarm/agent/jiuwenclaw_workspace),# 跟随 JIUWENSWARM_DATA_DIR 做多实例隔离,与 config.yaml 保持同一基准。from jiuwenswarm.common.utils import get_agent_workspace_dirdiff --git a/jiuwenswarm/common/file_transfer_config.py b/jiuwenswarm/common/file_transfer_config.pyindex 17b93b0624..764a4a1d48 100644--- a/jiuwenswarm/common/file_transfer_config.py+++ b/jiuwenswarm/common/file_transfer_config.py@@ -22,7 +22,7 @@ class FileTransferConfig:chunk_size: 分片大小(字节),默认 64KBmax_file_size: 最大文件大小(字节),默认 100MB,0=不限制transfer_timeout: 传输超时时间(秒),默认 300 秒- received_files_dir: 接收文件存储目录,默认 "agent/workspace/received_files"+ received_files_dir: 接收文件存储目录,默认 "agent/jiuwenclaw_workspace/received_files"cleanup_interval: 临时文件清理间隔(秒),默认 3600 秒cleanup_age: 清理超过 N 秒的临时文件,默认 86400 秒(24小时)max_concurrent_transfers: 最大并发传输数,默认 5@@ -32,7 +32,7 @@ class FileTransferConfig:chunk_size: int = 65536max_file_size: int = 104857600transfer_timeout: int = 300- received_files_dir: str = "agent/workspace/received_files"+ received_files_dir: str = "agent/jiuwenclaw_workspace/received_files"cleanup_interval: int = 3600cleanup_age: int = 86400max_concurrent_transfers: int = 5@@ -46,7 +46,7 @@ class FileTransferConfig:"max_file_size": int(data.get("max_file_size", 104857600)),"transfer_timeout": int(data.get("transfer_timeout", 300)),"received_files_dir": str(- data.get("received_files_dir", "agent/workspace/received_files")+ data.get("received_files_dir", "agent/jiuwenclaw_workspace/received_files")),"cleanup_interval": int(data.get("cleanup_interval", 3600)),"cleanup_age": int(data.get("cleanup_age", 86400)),diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.pyindex 232c0827d0..e538009c3e 100644--- a/jiuwenswarm/common/utils.py+++ b/jiuwenswarm/common/utils.py@@ -10,7 +10,7 @@ Runtime layout:- <root>/config/config.yaml- <root>/config/.env- <root>/agent/home-- <root>/agent/workspace(DeepAgent 标准工作空间)+- <root>/agent/jiuwenclaw_workspace(DeepAgent 标准工作空间)- memory/- skills/- todo/@@ -22,7 +22,7 @@ Runtime layout:- HEARTBEAT.md- USER.md- <root>/agent/sessions-- <root>/agent/workspace/agent-data.json+- <root>/agent/jiuwenclaw_workspace/agent-data.json- <root>/agent/.checkpoint- <root>/agent/.logs(gateway.log / channel.log / agent_server.log / full.log)@@ -904,42 +904,211 @@ def _migrate_from_jiuwenclaw_root() -> bool:return False-def _migrate_jiuwenclaw_workspace_to_workspace(workspace_dir: Path) -> None:- """Migrate from legacy jiuwenclaw_workspace directory name to workspace.+def _replace_path_prefix(value: str, prefixes: list[tuple[str, str]]) -> str:+ """替换字符串开头的旧工作区绝对路径前缀(分隔符边界感知)。++ 前缀命中后必须紧跟路径分隔符或结尾,避免误伤+ ``.../agent/workspace_other`` 这类路径。旧/新前缀各自的分隔符风格+ (``\\`` / ``/``)都处理。+ """+ for old_s, new_s in prefixes:+ if value == old_s:+ return new_s+ if value.startswith(old_s) and value[len(old_s)] in ("\\", "/"):+ return new_s + value[len(old_s):]+ return value+++def _rewrite_json_path_prefix(+ file_path: Path, prefixes: list[tuple[str, str]]+) -> bool:+ """重写 JSON 文件字符串值中的旧路径前缀;有变更并成功写回时返回 True。++ 解析后按值替换(避免 JSON 转义导致的文本替换错位),原子写回。+ 文件缺失/损坏时静默返回 False。+ """+ try:+ data = json.loads(file_path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return False++ changed = False++ def _rewrite(obj: Any) -> Any:+ nonlocal changed+ if isinstance(obj, str):+ new_value = _replace_path_prefix(obj, prefixes)+ if new_value != obj:+ changed = True+ obj = new_value+ return obj+ if isinstance(obj, list):+ return [_rewrite(item) for item in obj]+ if isinstance(obj, dict):+ return {key: _rewrite(value) for key, value in obj.items()}+ return obj++ new_data = _rewrite(data)+ if not changed:+ return False+ tmp_path = file_path.with_suffix(file_path.suffix + ".migration.tmp")+ try:+ tmp_path.write_text(+ json.dumps(new_data, ensure_ascii=False, indent=2), encoding="utf-8"+ )+ tmp_path.replace(file_path)+ except OSError as exc:+ tmp_path.unlink(missing_ok=True)+ logger.warning("重写 %s 中的旧路径前缀失败: %s", file_path, exc)+ return False+ return True+++def _rewrite_legacy_project_dir_metadata(+ agent_root: Path, old_workspace: Path, new_workspace: Path+) -> None:+ """目录改名后同步重写持久化元数据中的旧工作区绝对路径。++ 存量 ``projects.json``(``project_dir``)与 ``sessions/*/metadata.json``+ (``project_dir``、``channel_metadata.cwd`` 等)记录的是+ ``.../agent/workspace`` 绝对路径。若不重写,``validate_project_dir`` 会在+ 旧路径上 mkdir 重建"僵尸目录",下次重启又触发一轮合并迁移,且两次重启+ 之间写入旧目录的项目文件对会话不可见。++ 幂等:无旧前缀命中时不写盘,可安全重复调用(含并发迁移场景)。+ """+ old_s, new_s = str(old_workspace), str(new_workspace)+ posix_old, posix_new = old_workspace.as_posix(), new_workspace.as_posix()+ prefixes = [(old_s, new_s)]+ if posix_old != old_s:+ prefixes.append((posix_old, posix_new))++ projects_file = agent_root / "projects.json"+ if projects_file.is_file() and _rewrite_json_path_prefix(projects_file, prefixes):+ print(f"[migration] Rewrote legacy project_dir in {projects_file}")++ sessions_dir = agent_root / "sessions"+ if sessions_dir.is_dir():+ for entry in sessions_dir.iterdir():+ if not entry.is_dir():+ continue+ meta_file = entry / "metadata.json"+ if meta_file.is_file() and _rewrite_json_path_prefix(meta_file, prefixes):+ print(f"[migration] Rewrote legacy project_dir in {meta_file}")+++def _migrate_workspace_to_jiuwenclaw_workspace(workspace_dir: Path) -> None:+ """Migrate from legacy workspace directory name to jiuwenclaw_workspace.Migration:- - Old: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/- - New: ~/.jiuwenswarm/agent/workspace/+ - Old: <tenant_root>/agent/workspace/+ - New: <tenant_root>/agent/jiuwenclaw_workspace/++ Covers every tenant layout:+ - Personal: ``~/.jiuwenswarm/service_default/agent_default``+ - Enterprise: ``~/.jiuwenswarm/workspace_{key}`` for each key bucket+ - Legacy pre-tenant: ``~/.jiuwenswarm`` itselfArgs:workspace_dir: Path to workspace root (~/.jiuwenswarm)."""- old_workspace = workspace_dir / "agent" / "jiuwenclaw_workspace"- new_workspace = workspace_dir / "agent" / "workspace"- if not old_workspace.exists():- return- if new_workspace.exists():- # Both exist - merge carefully- print(f"[migration] Both jiuwenclaw_workspace and workspace exist, merging...")- for item in old_workspace.iterdir():- dest = new_workspace / item.name- if item.is_dir():- if dest.exists():- # Merge directories- shutil.copytree(item, dest, dirs_exist_ok=True)- else:- shutil.copytree(item, dest)+ def _merge_one(tenant_root: Path) -> None:+ agent_root = tenant_root / "agent"+ old_workspace = agent_root / "workspace"+ new_workspace = agent_root / "jiuwenclaw_workspace"+ if not old_workspace.exists():+ # 旧目录已不存在:可能是并发进程刚完成迁移(可能来不及重写元数据+ # 就崩溃),仍需重写元数据兜底(幂等,无命中不写盘)。+ _rewrite_legacy_project_dir_metadata(agent_root, old_workspace, new_workspace)+ return++ def _conflict_backup_dir() -> Path:+ """同名冲突时备份旧侧文件的目录(按时间戳隔离多次迁移)。++ 放在 ``agent/`` 下的隐藏同级目录(与 ``.checkpoint``/``.logs``+ 布局一致),不污染新工作区文件树。+ """+ backup_dir = agent_root / f".migration-backup-{int(time.time())}"+ backup_dir.mkdir(parents=True, exist_ok=True)+ return backup_dir++ try:+ if new_workspace.exists():+ # Both exist - merge carefully+ # 优先级方向统一为:新侧(jiuwenclaw_workspace)为胜者,旧侧独有内容并入;+ # 旧侧同名冲突文件一律备份到 agent/.migration-backup-{ts}/ 而非静默丢弃/覆盖。+ print(f"[migration] Both workspace and jiuwenclaw_workspace exist, merging...")+ backup_dir: Optional[Path] = None+ for item in old_workspace.iterdir():+ dest = new_workspace / item.name+ if item.is_dir():+ if dest.exists():+ # Merge directories, keeping new-side files on conflict+ # (same priority direction as top-level files below).+ for sub in item.rglob("*"):+ dest_sub = dest / sub.relative_to(item)+ if sub.is_dir():+ dest_sub.mkdir(parents=True, exist_ok=True)+ elif not dest_sub.exists():+ shutil.copy2(sub, dest_sub)+ else:+ # Conflict inside directory: back up old-side file+ if backup_dir is None:+ backup_dir = _conflict_backup_dir()+ backup_sub = backup_dir / item.name / sub.relative_to(item)+ backup_sub.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(sub, backup_sub)+ logger.warning(+ "Both workspace and jiuwenclaw_workspace have %s; "+ "kept new version, old copy backed up to %s",+ sub.relative_to(item), backup_sub,+ )+ else:+ shutil.copytree(item, dest)+ else:+ if not dest.exists():+ shutil.copy2(item, dest)+ else:+ # Conflict: back up old-side file instead of dropping it+ if backup_dir is None:+ backup_dir = _conflict_backup_dir()+ backup_path = backup_dir / item.name+ shutil.copy2(item, backup_path)+ logger.warning(+ "Both workspace and jiuwenclaw_workspace have %s; "+ "kept new version, old copy backed up to %s",+ item.name, backup_path,+ )+ # Remove old after successful merge+ shutil.rmtree(old_workspace)+ print(f"[migration] Merged and removed: {old_workspace}")else:- if not dest.exists():- shutil.copy2(item, dest)- # Remove old after successful merge- shutil.rmtree(old_workspace)- print(f"[migration] Merged and removed: {old_workspace}")- else:- # Simple rename- shutil.move(str(old_workspace), str(new_workspace))- print(f"[migration] Renamed: {old_workspace} -> {new_workspace}")+ # Simple rename+ shutil.move(str(old_workspace), str(new_workspace))+ print(f"[migration] Renamed: {old_workspace} -> {new_workspace}")+ except FileNotFoundError:+ # 多进程/多 Pod 并发启动时,旧目录可能已被其他进程迁移/清理。+ # 此时迁移目标已达成,跳过而非崩溃。+ print(+ f"[migration] {old_workspace} already handled by another process, skipping"+ )+ # 无论迁移由本进程还是并发进程完成,都重写元数据中的旧路径前缀+ # (幂等,无命中不写盘)。+ _rewrite_legacy_project_dir_metadata(agent_root, old_workspace, new_workspace)++ tenant_roots = [workspace_dir / "service_default" / "agent_default"]+ if workspace_dir.is_dir():+ tenant_roots.extend(+ entry for entry in workspace_dir.iterdir()+ if entry.is_dir() and entry.name.startswith("workspace_")+ )+ for tenant_root in tenant_roots:+ if (tenant_root / "agent").is_dir():+ _merge_one(tenant_root)+ # Legacy pre-tenant layout: <root>/agent/workspace+ if (workspace_dir / "agent").is_dir():+ _merge_one(workspace_dir)def _migrate_legacy_workspace(@@ -956,15 +1125,15 @@ def _migrate_legacy_workspace(- Old: ~/.jiuwenswarm/agent/skills/- Old: ~/.jiuwenswarm/agent/memory/- - New: ~/.jiuwenswarm/agent/workspace/ (DeepAgent standard)+ - New: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/ (DeepAgent standard)Mapping:- - agent/home/HEARTBEAT.md -> agent/workspace/HEARTBEAT.md- - agent/skills/ -> agent/workspace/skills/- - agent/memory/ -> agent/workspace/memory/+ - agent/home/HEARTBEAT.md -> agent/jiuwenclaw_workspace/HEARTBEAT.md+ - agent/skills/ -> agent/jiuwenclaw_workspace/skills/+ - agent/memory/ -> agent/jiuwenclaw_workspace/memory/- Note: jiuwenclaw_workspace -> workspace renaming is handled separately by- _migrate_jiuwenclaw_workspace_to_workspace.+ Note: workspace -> jiuwenclaw_workspace renaming is handled separately by+ _migrate_workspace_to_jiuwenclaw_workspace.Args:workspace_dir: Path to workspace root (~/.jiuwenswarm).@@ -976,7 +1145,7 @@ def _migrate_legacy_workspace(old_skills = workspace_dir / "agent" / "skills"old_memory = workspace_dir / "agent" / "memory"- new_workspace = workspace_dir / "agent" / "workspace"+ new_workspace = workspace_dir / "agent" / "jiuwenclaw_workspace"new_workspace.mkdir(parents=True, exist_ok=True)# 1. Migrate old home files@@ -1226,8 +1395,8 @@ def prepare_workspace(workspace_dir.mkdir(parents=True, exist_ok=True)migrate_legacy_user_config_if_needed()- # Migrate from legacy jiuwenclaw_workspace directory name to workspace- _migrate_jiuwenclaw_workspace_to_workspace(workspace_dir)+ # Migrate from legacy workspace directory name to jiuwenclaw_workspace+ _migrate_workspace_to_jiuwenclaw_workspace(workspace_dir)# Check for legacy workspace migration or cleanup (pre-DeepAgent layout)# These are even older layouts: agent/workspace, agent/home, agent/skills, agent/memory@@ -1337,7 +1506,7 @@ def prepare_workspace(agent_sessions = agent_root / "sessions"# ----- DeepAgent workspace (standard DeepAgents schema) ------ deepagent_workspace = agent_root / "workspace"+ deepagent_workspace = agent_root / "jiuwenclaw_workspace"default_project_workspace = deepagent_workspace / "projects"agent_skills = deepagent_workspace / "skills"agent_memory = deepagent_workspace / "memory"@@ -1604,15 +1773,15 @@ def _resolve_paths(force=False) -> None:workspace_dir = get_user_workspace_dir()- # Migrate from legacy jiuwenclaw_workspace directory name to workspace- _migrate_jiuwenclaw_workspace_to_workspace(workspace_dir)+ # Migrate from legacy workspace directory name to jiuwenclaw_workspace+ _migrate_workspace_to_jiuwenclaw_workspace(workspace_dir)# 优先使用已初始化的用户工作区 (~/.jiuwenswarm),# 保证源码运行与安装包运行后的读写路径完全一致。user_config_dir = workspace_dir / "config"# 租户默认工作区:个人版 service_default/agent_default;企业版 workspace_defaultmulti_tenant_workspace = get_multi_tenant_user_workspace_dir("default")- user_workspace_dir = multi_tenant_workspace / "agent" / "workspace"+ user_workspace_dir = multi_tenant_workspace / "agent" / "jiuwenclaw_workspace"if user_config_dir.exists():_root_dir = workspace_dir_config_dir = user_config_dir@@ -1674,7 +1843,7 @@ def get_agent_workspace_dir() -> Path:Returns:Path to agent workspace:- ``~/.jiuwenswarm/workspace_default/agent/workspace``+ ``~/.jiuwenswarm/workspace_default/agent/jiuwenclaw_workspace``(or the request-bound tenant workspace when ContextVar is set)."""try:@@ -1685,7 +1854,7 @@ def get_agent_workspace_dir() -> Path:return boundexcept ImportError:logger.debug("tenant_context unavailable for workspace bind", exc_info=True)- return get_agent_root_dir() / "workspace"+ return get_agent_root_dir() / "jiuwenclaw_workspace"def get_default_project_workspace_dir() -> Path:@@ -1764,7 +1933,7 @@ def get_agent_root_relative_dir() -> Path:def get_agent_workspace_relative_dir() -> Path:"""Get the agent workspace relative path under a tenant workspace root."""- return get_agent_root_relative_dir() / "workspace"+ return get_agent_root_relative_dir() / "jiuwenclaw_workspace"_AGENT_WORKSPACE_DIR_NAMES = frozenset({"workspace", "jiuwenclaw_workspace"})@@ -1773,8 +1942,8 @@ _AGENT_WORKSPACE_DIR_NAMES = frozenset({"workspace", "jiuwenclaw_workspace"})def collapse_nested_agent_workspace_dir(path: Path | str) -> Path:"""Collapse ``.../workspace/workspace`` back to the agent workspace.- The agent workspace is ``.../agent/workspace`` (this project) or- ``.../agent/jiuwenclaw_workspace`` (upstream). PPT tooling historically+ The agent workspace is ``.../agent/workspace`` (legacy name) or+ ``.../agent/jiuwenclaw_workspace`` (current). PPT tooling historicallyused ``{cwd}/workspace`` as the session parent, which nests a second``workspace`` directory when cwd is already the agent workspace."""@@ -1859,7 +2028,7 @@ def get_multi_tenant_user_workspace_dir(def get_tenant_agent_workspace_dir(workspace_key: str | None = None) -> Path:- """DeepAgent 工作区:``<tenant_root>/agent/workspace``.+ """DeepAgent 工作区:``<tenant_root>/agent/jiuwenclaw_workspace``.企业版 tenant_root 为 ``workspace_{key}``;个人版为 ``service_default/agent_default``。"""@@ -1875,7 +2044,7 @@ def get_tenant_agent_skills_dirs(workspace_key: str | None = None) -> list[Path]def get_multi_tenant_skill_dirs(workspace_key: str | None = None) -> list[Path]:"""Resolve the skills directory list for multi-tenant / single-tenant mode.- - 显式提供 ``workspace_key``: ``[<tenant_root>/agent/workspace/skills]``+ - 显式提供 ``workspace_key``: ``[<tenant_root>/agent/jiuwenclaw_workspace/skills]``(企业版 tenant_root=``workspace_{key}``,个人版固定 ``service_default/agent_default``)。- 未提供: ``[get_agent_skills_dir()]``(不读 bound key,避免误进多租户树)."""@@ -1894,7 +2063,7 @@ def get_agent_memory_dir() -> Path:Uses DeepAgent standard workspace location for unified workspace.Returns:- Path to memory directory: ~/.jiuwenswarm/agent/workspace/memory+ Path to memory directory: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/memory"""return get_agent_workspace_dir() / "memory"@@ -1905,7 +2074,7 @@ def get_agent_skills_dir() -> Path:Uses DeepAgent standard workspace location for unified workspace.Returns:- Path to skills directory: ~/.jiuwenswarm/agent/workspace/skills+ Path to skills directory: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/skills"""return get_agent_workspace_dir() / "skills"@@ -2009,7 +2178,7 @@ def get_interactions_dir() -> Path:"""Get the interactions directory for pending interaction contexts.Returns:- Path to interactions directory: {workspace}/agent/workspace/interactions+ Path to interactions directory: {workspace}/agent/jiuwenclaw_workspace/interactions"""return get_agent_workspace_dir() / "interactions"@@ -2070,8 +2239,8 @@ def resolve_tenant_agent_root_dir(workspace_key: str | None = None) -> Path:def resolve_tenant_agent_workspace_dir(workspace_key: str | None = None) -> Path:- """Resolve ``<tenant_root>/agent/workspace``."""- return resolve_tenant_agent_root_dir(workspace_key) / "workspace"+ """Resolve ``<tenant_root>/agent/jiuwenclaw_workspace``."""+ return resolve_tenant_agent_root_dir(workspace_key) / "jiuwenclaw_workspace"def resolve_tenant_sessions_dir(workspace_key: str | None = None) -> Path:@@ -2114,7 +2283,7 @@ def get_deepagent_todo_dir() -> Path:"""Get the DeepAgent todo directory path.Returns:- Path to todo directory: ~/.jiuwenswarm/agent/workspace/todo+ Path to todo directory: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/todo"""return get_agent_workspace_dir() / "todo"@@ -2123,7 +2292,7 @@ def get_deepagent_messages_dir() -> Path:"""Get the DeepAgent messages directory path.Returns:- Path to messages directory: ~/.jiuwenswarm/agent/workspace/messages+ Path to messages directory: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/messages"""return get_agent_workspace_dir() / "messages"@@ -2132,7 +2301,7 @@ def get_deepagent_agents_dir() -> Path:"""Get the DeepAgent agents (sub-agent) directory path.Returns:- Path to agents directory: ~/.jiuwenswarm/agent/workspace/agents+ Path to agents directory: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/agents"""return get_agent_workspace_dir() / "agents"@@ -2141,7 +2310,7 @@ def get_deepagent_heartbeat_path() -> Path:"""Get the DeepAgent HEARTBEAT.md file path.Returns:- Path to HEARTBEAT.md: ~/.jiuwenswarm/agent/workspace/HEARTBEAT.md+ Path to HEARTBEAT.md: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/HEARTBEAT.md"""return get_agent_workspace_dir() / "HEARTBEAT.md"@@ -2150,7 +2319,7 @@ def get_deepagent_agent_md_path() -> Path:"""Get the DeepAgent AGENT.md file path.Returns:- Path to AGENT.md: ~/.jiuwenswarm/agent/workspace/AGENT.md+ Path to AGENT.md: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/AGENT.md"""return get_agent_workspace_dir() / "AGENT.md"@@ -2159,7 +2328,7 @@ def get_deepagent_soul_md_path() -> Path:"""Get the DeepAgent SOUL.md file path.Returns:- Path to SOUL.md: ~/.jiuwenswarm/agent/workspace/SOUL.md+ Path to SOUL.md: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/SOUL.md"""return get_agent_workspace_dir() / "SOUL.md"@@ -2168,7 +2337,7 @@ def get_deepagent_identity_md_path() -> Path:"""Get the DeepAgent IDENTITY.md file path.Returns:- Path to IDENTITY.md: ~/.jiuwenswarm/agent/workspace/IDENTITY.md+ Path to IDENTITY.md: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/IDENTITY.md"""return get_agent_workspace_dir() / "IDENTITY.md"@@ -2177,7 +2346,7 @@ def get_deepagent_user_md_path() -> Path:"""Get the DeepAgent USER.md file path.Returns:- Path to USER.md: ~/.jiuwenswarm/agent/workspace/USER.md+ Path to USER.md: ~/.jiuwenswarm/agent/jiuwenclaw_workspace/USER.md"""return get_agent_workspace_dir() / "USER.md"@@ -3174,9 +3343,9 @@ async def reload_logging_levels() -> None:update_log_levels()returntry:- from jiuwenswarm.server.runtime.enterprise_config import db_queries+ from jiuwenswarm.server.runtime.enterprise_config import gateway_db- rows = await db_queries.list_records(_LOGGING_CONFIG_TABLE)+ rows = await gateway_db.list_records(_LOGGING_CONFIG_TABLE)row = rows[0] if rows else Noneapply_logging_config_payload(_logging_config_row_to_dict(row) if row is not None else None,diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 9d18ee09ae..b6567ae056 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -4417,7 +4417,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:"""创建项目,指定工作目录。``project_dir`` 为可选:传则指定工作目录绝对路径;不传或空串则在默认工作区- (``~/.jiuwenswarm/agent/workspace/{work|code}``)下按项目名自动新建文件夹作为工作目录。+ (``~/.jiuwenswarm/agent/jiuwenclaw_workspace/{work|code}``)下按项目名自动新建文件夹作为工作目录。``work_mode`` 为可选:``"code"`` / ``"work"``,默认按通道推断(Web→work,TUI→code)。项目名含文件系统非法字符(``<>:"/\\|?*`` 等)时返回 ``BAD_REQUEST``。自动恢复: 若 ``project_dir`` 命中已隐藏(``hidden:true``)**且同 work_mode**的项目,置diff --git a/jiuwenswarm/gateway/channel_manager/web/file_http.py b/jiuwenswarm/gateway/channel_manager/web/file_http.pyindex cd7b7c2c19..3bc9fc1264 100644--- a/jiuwenswarm/gateway/channel_manager/web/file_http.py+++ b/jiuwenswarm/gateway/channel_manager/web/file_http.py@@ -146,9 +146,9 @@ def _normalize_lang_suffix(name: str) -> str:def generate_agent_data(project_root: Path) -> None:- """Generate agent/workspace/agent-data.json from agent tree."""+ """Generate agent/jiuwenclaw_workspace/agent-data.json from agent tree."""agent_root = (project_root / "agent").resolve()- workspace_root = (agent_root / "workspace").resolve()+ workspace_root = (agent_root / "jiuwenclaw_workspace").resolve()output_path = (workspace_root / "agent-data.json").resolve()root_folder_key = "__root__"@@ -289,11 +289,22 @@ def read_file_text(if not is_path_under_allowed_root(roots, full_path):return 403, {"error": "forbidden_path"}, None, Noneif not full_path.exists():- if file_arg.replace("\\", "/") == "agent/workspace/agent-data.json":+ normalized_arg = file_arg.replace("\\", "/")+ if normalized_arg in (+ "agent/jiuwenclaw_workspace/agent-data.json",+ # legacy pre-rename path (old frontend caches / bookmarks)+ "agent/workspace/agent-data.json",+ ):try:generate_agent_data(roots.project_root)except Exception as exc: # noqa: BLE001return 500, {"error": "generate_failed", "detail": str(exc)}, None, None+ # generate_agent_data only writes to the new path; rewrite legacy+ # requests to it so the caller actually receives the data.+ if normalized_arg == "agent/workspace/agent-data.json":+ full_path = (+ roots.project_root / "agent" / "jiuwenclaw_workspace" / "agent-data.json"+ ).resolve()if not full_path.exists():return (404,diff --git a/jiuwenswarm/gateway/routing/interaction_context.py b/jiuwenswarm/gateway/routing/interaction_context.pyindex 0094a8b0bf..79cc448fc6 100644--- a/jiuwenswarm/gateway/routing/interaction_context.py+++ b/jiuwenswarm/gateway/routing/interaction_context.py@@ -2,7 +2,7 @@"""PendingInteraction — 统一的追问上下文,支持群聊追问和 DM 追问两种模式。-存储路径: {workspace_dir}/agent/workspace/interactions/{interaction_id}.json+存储路径: {workspace_dir}/agent/jiuwenclaw_workspace/interactions/{interaction_id}.json文件名前缀: gpq_* 群聊追问, iact_* DM 追问TTL: 24 小时"""diff --git a/jiuwenswarm/gateway/tenant_paths.py b/jiuwenswarm/gateway/tenant_paths.pyindex 4f244c5d95..3333f61290 100644--- a/jiuwenswarm/gateway/tenant_paths.py+++ b/jiuwenswarm/gateway/tenant_paths.py@@ -76,10 +76,10 @@ def tenant_ids_from_message(msg: Any) -> tuple[str, str]:def resolve_channel_agent_workspace(workspace_key: str | None = None) -> Path:- """``<tenant_root>/agent/workspace``(经 ``get_multi_tenant_user_workspace_dir``)。"""+ """``<tenant_root>/agent/jiuwenclaw_workspace``(经 ``get_multi_tenant_user_workspace_dir``)。"""wk = normalize_tenant_scope_id(workspace_key)base = get_multi_tenant_user_workspace_dir(wk)- return base / "agent" / "workspace"+ return base / "agent" / "jiuwenclaw_workspace"def resolve_channel_group_chat_memory_dir(workspace_key: str | None = None) -> Path:diff --git a/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/SKILL.mdindex ab440e1975..acc633200e 100644--- a/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/SKILL.md+++ b/jiuwenswarm/resources/agent/workspace/skills/advanced-daily-report/SKILL.md@@ -76,7 +76,7 @@ daily-report/**脚本会自动采集以下数据**:- **Git 提交记录**:通过 `git log` 命令读取 `D:/Download/jiuwenswarm` 仓库的提交历史- **邮箱邮件统计**:通过 IMAP 协议连接 `.env` 中配置的邮箱账户读取邮件统计(需要邮箱授权码)-- **记忆系统**:读取 `~/.jiuwenswarm/agent/workspace/memory/` 目录下的每日记忆文件+- **记忆系统**:读取 `~/.jiuwenswarm/agent/jiuwenclaw_workspace/memory/` 目录下的每日记忆文件- **待办事项**:读取 `~/.jiuwenswarm/agent/sessions/` 下各会话的 `todo.md` 文件### 手动触发@@ -85,19 +85,19 @@ daily-report/```bash# 生成今日日报(记忆/待办/Git 等;Git 在仓库根目录统计)-python ~/.jiuwenswarm/agent/workspace/skills/daily-report/run_report.py daily --save+python ~/.jiuwenswarm/agent/jiuwenclaw_workspace/skills/daily-report/run_report.py daily --save# 生成指定日期日报-python ~/.jiuwenswarm/agent/workspace/skills/daily-report/run_report.py daily --date 2026-03-06 --save+python ~/.jiuwenswarm/agent/jiuwenclaw_workspace/skills/daily-report/run_report.py daily --date 2026-03-06 --save# 生成周报(聚合一周数据)-python ~/.jiuwenswarm/agent/workspace/skills/daily-report/run_report.py weekly --save+python ~/.jiuwenswarm/agent/jiuwenclaw_workspace/skills/daily-report/run_report.py weekly --save# 生成月报(聚合一月数据,包含每日Git提交统计)-python ~/.jiuwenswarm/agent/workspace/skills/daily-report/run_report.py monthly --save+python ~/.jiuwenswarm/agent/jiuwenclaw_workspace/skills/daily-report/run_report.py monthly --save# 生成月报(指定月份)-python ~/.jiuwenswarm/agent/workspace/skills/daily-report/run_report.py monthly --year 2026 --month 3 --save+python ~/.jiuwenswarm/agent/jiuwenclaw_workspace/skills/daily-report/run_report.py monthly --year 2026 --month 3 --save```### 执行步骤@@ -127,7 +127,7 @@ python ~/.jiuwenswarm/agent/workspace/skills/daily-report/run_report.py monthly|--------|----------|----------|| **Git 仓库** | `git log` 命令 | 仓库路径: `D:/Download/jiuwenswarm` || **网易邮箱** | IMAP 协议 | `.env`: `EMAIL_ADDRESS`, `EMAIL_TOKEN` |-| **记忆系统** | 读取 MD 文件 | `~/.jiuwenswarm/agent/workspace/memory/YYYY-MM-DD.md` |+| **记忆系统** | 读取 MD 文件 | `~/.jiuwenswarm/agent/jiuwenclaw_workspace/memory/YYYY-MM-DD.md` || **待办事项** | 解析 todo.md | `~/.jiuwenswarm/agent/sessions/*/todo.md` |### 定时触发diff --git a/jiuwenswarm/resources/agent/workspace/skills/akg-agents/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/akg-agents/SKILL.mdindex 2cf8d5e525..e3207fa176 100644--- a/jiuwenswarm/resources/agent/workspace/skills/akg-agents/SKILL.md+++ b/jiuwenswarm/resources/agent/workspace/skills/akg-agents/SKILL.md@@ -20,7 +20,7 @@ description: 代理执行 AKG 算子任务。先检查固定仓库与分支;- `<AKG_REPO_URL>`:`https://gitcode.com/mindspore/akg/`- `<AKG_REPO_BRANCH>`:`br_agents`-- `<AKG_REPO_DIR>`:`$HOME/.jiuwenswarm/agent/workspace/akg`+- `<AKG_REPO_DIR>`:`$HOME/.jiuwenswarm/agent/jiuwenclaw_workspace/akg`- `<AKG_AGENTS_DIR>`:`<AKG_REPO_DIR>/akg_agents`先检查 `<AKG_REPO_DIR>` 是否存在;若存在,再检查它是否为 git 仓库以及当前分支是否为 `<AKG_REPO_BRANCH>`。diff --git a/jiuwenswarm/resources/agent/workspace/skills/ascend-moe-optimizer-trace-analyzer/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/ascend-moe-optimizer-trace-analyzer/SKILL.mdindex 489f193671..8e0283a059 100644--- a/jiuwenswarm/resources/agent/workspace/skills/ascend-moe-optimizer-trace-analyzer/SKILL.md+++ b/jiuwenswarm/resources/agent/workspace/skills/ascend-moe-optimizer-trace-analyzer/SKILL.md@@ -15,7 +15,7 @@ description: 在用户提供 Chrome/Perfetto trace.json、或排查 Ascend 上 M## 脚本位置-- 用户安装后的 skill 根目录:`<ASCEND_MOE_OPTIMIZER_SKILL>` = `~/.jiuwenswarm/agent/workspace/skills/ascend-moe-optimizer-trace-analyzer`+- 用户安装后的 skill 根目录:`<ASCEND_MOE_OPTIMIZER_SKILL>` = `~/.jiuwenswarm/agent/jiuwenclaw_workspace/skills/ascend-moe-optimizer-trace-analyzer`- 入口:`<ASCEND_MOE_OPTIMIZER_SKILL>/app.py`- 从本仓库资源运行时,将上述路径换为 `jiuwenswarm/resources/agent/workspace/skills/ascend-moe-optimizer-trace-analyzer`(相对仓库根目录)。diff --git a/jiuwenswarm/resources/agent/workspace/skills/cross-channel-history-retrieval/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/cross-channel-history-retrieval/SKILL.mdindex 5c627e8f09..bd6b0aa8e2 100644--- a/jiuwenswarm/resources/agent/workspace/skills/cross-channel-history-retrieval/SKILL.md+++ b/jiuwenswarm/resources/agent/workspace/skills/cross-channel-history-retrieval/SKILL.md@@ -21,7 +21,7 @@ allowed_tools: [mcp_exec_command]必须使用 `mcp_exec_command` 执行脚本,不要只口头总结。```bash-python ~/.jiuwenswarm/agent/workspace/skills/cross-channel-history-retrieval/scripts/search_history.py --channel feishu --query "报销 审批" --start "2026-03-26 09:00" --end "2026-03-26 18:00" --limit 30+python ~/.jiuwenswarm/agent/jiuwenclaw_workspace/skills/cross-channel-history-retrieval/scripts/search_history.py --channel feishu --query "报销 审批" --start "2026-03-26 09:00" --end "2026-03-26 18:00" --limit 30```(Windows:**`--channel` / `--query` / 时间参数等与 Unix 相同**;默认 `mcp_exec_command` 走 **cmd**,**cmd 不会展开 `~`**,不要用 `~/.jiuwenswarm`,应写 `python %USERPROFILE%\.jiuwenswarm\agent\skills\cross-channel-history-retrieval\scripts\search_history.py` 再接同样参数。若整条命令在 PowerShell 里执行,`~` 一般会展开,也可用 `$env:USERPROFILE\...`。)diff --git a/jiuwenswarm/resources/agent/workspace/skills/delayed-restart-app/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/delayed-restart-app/SKILL.mdindex 1a2829834a..0cb9614454 100644--- a/jiuwenswarm/resources/agent/workspace/skills/delayed-restart-app/SKILL.md+++ b/jiuwenswarm/resources/agent/workspace/skills/delayed-restart-app/SKILL.md@@ -21,7 +21,7 @@ description: 安排延迟重启本 Agent 所在的服务(JiuwenSwarm app)。python %USERPROFILE%\.jiuwenswarm\agent\skills\delayed-restart-app\launch_delayed_restart.py --pid <当前 app 的 PID> --delay 5```-(Unix/macOS 使用:`python ~/.jiuwenswarm/agent/workspace/skills/delayed-restart-app/launch_delayed_restart.py --pid <PID> --delay 5`)+(Unix/macOS 使用:`python ~/.jiuwenswarm/agent/jiuwenclaw_workspace/skills/delayed-restart-app/launch_delayed_restart.py --pid <PID> --delay 5`)- `--pid`:必填,当前 JiuwenSwarm app 进程的 PID(执行前需先获取,如从 config 或通过 `tasklist`/`pgrep` 等命令)- `--delay 5`:延迟 5 秒后重启(可改为 3、10 等)diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/sync-runtime-skill.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/sync-runtime-skill.jsindex e93b61d8d0..ce729e57a6 100644--- a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/sync-runtime-skill.js+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/sync-runtime-skill.js@@ -14,11 +14,11 @@ const crypto = require("crypto");const SRC = path.resolve(__dirname, ".."); // .../skills/ppt-creation (repo copy)const DST = path.resolve(- process.env.HOME, ".jiuwenswarm/agent/workspace/skills/ppt-creation" // runtime copy+ process.env.HOME, ".jiuwenswarm/agent/jiuwenclaw_workspace/skills/ppt-creation" // runtime copy);const AGENT_DATA = [path.resolve(SRC, "../../agent-data.json"), // repo manifest- path.resolve(process.env.HOME, ".jiuwenswarm/agent/workspace/agent-data.json"), // runtime manifest+ path.resolve(process.env.HOME, ".jiuwenswarm/agent/jiuwenclaw_workspace/agent-data.json"), // runtime manifest];const EXCLUDE_DIRS = new Set(["node_modules", "output", ".git"]);@@ -145,8 +145,8 @@ function reconcileManifest(manifestPath) {data[key].push({name,path: dirRel- ? `agent/workspace/skills/ppt-creation/${dirRel}/${name}`- : `agent/workspace/skills/ppt-creation/${name}`,+ ? `agent/jiuwenclaw_workspace/skills/ppt-creation/${dirRel}/${name}`+ : `agent/jiuwenclaw_workspace/skills/ppt-creation/${name}`,isMarkdown: name.endsWith(".md"),});added += 1;diff --git a/jiuwenswarm/resources/agent/workspace/skills/skill-omni-creation/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/skill-omni-creation/SKILL.mdindex 42e3cfca7e..f0358438ab 100644--- a/jiuwenswarm/resources/agent/workspace/skills/skill-omni-creation/SKILL.md+++ b/jiuwenswarm/resources/agent/workspace/skills/skill-omni-creation/SKILL.md@@ -142,7 +142,7 @@ cd {skill_directory}/scripts && python3 save_images.py <slug> '["raw_images/dom_```[save_images] img_00.jpg <- raw_images/dom_002.jpg[save_images] img_01.png <- raw_images/dom_005.png-[save_images] SKILL_MD_PATH: /Users/xxx/.jiuwenswarm/agent/workspace/skills/exposure_fusion_opencv/SKILL.md+[save_images] SKILL_MD_PATH: /Users/xxx/.jiuwenswarm/agent/jiuwenclaw_workspace/skills/exposure_fusion_opencv/SKILL.md```**生成 SKILL.md 时,用 write_file 写入 `SKILL_MD_PATH` 打印出的绝对路径。图片路径为 `references/<文件名>`,例如 `references/img_00.jpg`。**diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 68b2a4948d..0842a103ec 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -1339,7 +1339,7 @@ file_transfer:chunk_size: 65536max_file_size: 104857600transfer_timeout: 300- received_files_dir: "agent/workspace/received_files"+ received_files_dir: "agent/jiuwenclaw_workspace/received_files"cleanup_interval: 3600cleanup_age: 86400max_concurrent_transfers: 5diff --git a/jiuwenswarm/scripts/generate-agent-folders.js b/jiuwenswarm/scripts/generate-agent-folders.jsindex 4b35f1dab8..581e133a0b 100644--- a/jiuwenswarm/scripts/generate-agent-folders.js+++ b/jiuwenswarm/scripts/generate-agent-folders.js@@ -15,7 +15,12 @@ if (!agentRoot) {process.exit(1);}-const outputPath = path.join(agentRoot, 'workspace', 'agent-data.json');+// Runtime installs use agent/jiuwenclaw_workspace; the in-package template keeps agent/workspace.+const runtimeWorkspace = path.join(agentRoot, 'jiuwenclaw_workspace');+const outputPath = path.join(+ fs.existsSync(runtimeWorkspace) ? runtimeWorkspace : path.join(agentRoot, 'workspace'),+ 'agent-data.json'+);console.log('扫描目录:', agentRoot);diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.pyindex 8bc2e579eb..bf2bf1e65f 100644--- a/jiuwenswarm/server/app_agentserver.py+++ b/jiuwenswarm/server/app_agentserver.py@@ -43,8 +43,8 @@ migrate_legacy_user_config_if_needed()# Ensure workspace initialized_workspace_dir = get_user_workspace_dir()_config_file = _workspace_dir / "config" / "config.yaml"-_new_workspace = _workspace_dir / "agent" / "workspace"-_old_workspace = _workspace_dir / "agent" / "jiuwenclaw_workspace"+_new_workspace = _workspace_dir / "agent" / "jiuwenclaw_workspace"+_old_workspace = _workspace_dir / "agent" / "workspace"if not _config_file.exists() or (_old_workspace.exists() and not _new_workspace.exists()):prepare_workspace(overwrite=False)else:diff --git a/jiuwenswarm/server/handlers/_shared.py b/jiuwenswarm/server/handlers/_shared.pyindex 67d06e2204..1f1c0f43b5 100644--- a/jiuwenswarm/server/handlers/_shared.py+++ b/jiuwenswarm/server/handlers/_shared.py@@ -218,7 +218,7 @@ def _sessions_dir_for_request(request: AgentRequest) -> Path:def _agent_workspace_dir_for_request(request: AgentRequest) -> Path:- """Resolve tenant ``workspace_{key}/agent/workspace`` for a request."""+ """Resolve tenant ``workspace_{key}/agent/jiuwenclaw_workspace`` for a request."""_agent_id, _service_id, workspace_key = TenantAgentPool.extract_ids(request)return resolve_tenant_agent_workspace_dir(workspace_key)diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex defc60b423..a840b4a55f 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -1170,7 +1170,9 @@ class JiuWenSwarm:user_ws = getattr(self, "_user_workspace_dir", None)if user_ws is not None:return str(- collapse_nested_agent_workspace_dir(Path(user_ws) / "agent" / "workspace")+ collapse_nested_agent_workspace_dir(+ Path(user_ws) / "agent" / "jiuwenclaw_workspace"+ ))return str(collapse_nested_agent_workspace_dir(get_agent_workspace_dir()))diff --git a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.pyindex 1c3dcbd4e7..a397ced230 100644--- a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py+++ b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py@@ -129,7 +129,7 @@ def _resolve_shared_dir(shared_dir: str | Path | None = None) -> Path | None:Prefer an explicit ``shared_dir`` (enterprise multi-tenant workspace).Otherwise mount ``get_agent_root_dir()`` (e.g. ``~/.jiuwenswarm/agent``)- rather than only ``agent/workspace``, so sibling download paths remain writable.+ rather than only ``agent/jiuwenclaw_workspace``, so sibling download paths remain writable."""try:if shared_dir is not None and str(shared_dir).strip():diff --git a/jiuwenswarm/server/runtime/session/project_store.py b/jiuwenswarm/server/runtime/session/project_store.pyindex d8887950e2..89eaf6d95d 100644--- a/jiuwenswarm/server/runtime/session/project_store.py+++ b/jiuwenswarm/server/runtime/session/project_store.py@@ -762,7 +762,7 @@ def resolve_default_project_dir("""根据项目名 + work_mode 在默认工作区下生成工作目录绝对路径。创建项目未指定 ``project_dir`` 时,在- ``~/.jiuwenswarm/agent/workspace/{code|work}/{name}`` 下按项目名生成工作目录。+ ``~/.jiuwenswarm/agent/jiuwenclaw_workspace/{code|work}/{name}`` 下按项目名生成工作目录。``code`` 与 ``work`` 模式使用不同子目录,使默认创建路径与跨模式项目隔离目标一致,避免同名 code/work 项目默认创建落到同一路径。@@ -781,7 +781,7 @@ def resolve_default_project_dir("""dir_name = validate_project_dir_name(name)mode = _normalize_work_mode_value(work_mode)- return str(get_agent_root_dir() / "workspace" / mode / dir_name)+ return str(get_agent_root_dir() / "jiuwenclaw_workspace" / mode / dir_name)def create_project(diff --git a/jiuwenswarm/server/runtime/session/session_metadata.py b/jiuwenswarm/server/runtime/session/session_metadata.pyindex 7dc773d97e..dd287c0b7e 100644--- a/jiuwenswarm/server/runtime/session/session_metadata.py+++ b/jiuwenswarm/server/runtime/session/session_metadata.py@@ -170,6 +170,23 @@ def _apply_metadata_defaults_with_inference(changed = False # 是否有需要写盘的确定性推断+ # 惰性迁移:历史 .../agent/workspace 前缀重映射到 jiuwenclaw_workspace。+ # 与 project_dir 的"首次锁定不可改"语义不冲突:重映射前后指向同一逻辑目录,+ # 不重写会导致旧前缀命中 dir_to_projects 失败、且 mkdir 复活僵尸目录。+ remapped_dir = _remap_legacy_workspace_prefix(+ str(metadata.get("project_dir") or "")+ )+ if remapped_dir != metadata["project_dir"]:+ metadata["project_dir"] = remapped_dir+ changed = True+ if isinstance(metadata.get("channel_metadata"), dict):+ for key in ("cwd", "project_dir"):+ legacy_val = str(metadata["channel_metadata"].get(key) or "")+ remapped_val = _remap_legacy_workspace_prefix(legacy_val)+ if remapped_val != legacy_val:+ metadata["channel_metadata"][key] = remapped_val+ changed = True+# last_user_message_at: 多级回退# 优先用已有时间字段;不能用 ``or`` 短路——合法的 0.0 时间戳是 falsy。if "last_user_message_at" not in metadata:@@ -445,10 +462,47 @@ def restore_session_team_binding_artifacts(_METADATA_CACHE.pop(_metadata_cache_key(session_id, root_s), None)+def _remap_legacy_workspace_prefix(path: str) -> str:+ """将历史的 ``.../agent/workspace`` 前缀重映射到 ``.../agent/jiuwenclaw_workspace``。++ 目录改名迁移(utils._migrate_workspace_to_jiuwenclaw_workspace)会重写+ projects.json / metadata.json,但仍可能有遗漏记录(如迁移后手动恢复的+ 备份文件)。此处兜底重映射,避免在旧路径上 mkdir 重建"僵尸目录",+ 导致下次重启再触发一轮合并迁移、两次重启间写入的文件对会话不可见。++ 仅当旧路径本身已不存在而新路径存在时才重映射(迁移未完成的场景保持原样)。+ """+ raw = (path or "").strip()+ if not raw:+ return raw+ # 逐级向上寻找 .../agent/workspace 锚点(basename/dirname 屏蔽分隔符差异,+ # 兼容 ``\\`` 与 ``/`` 两种风格;取最深层命中,与迁移重写的前缀语义一致)+ normalized = os.path.normpath(raw)+ current = normalized+ while current and current != os.path.dirname(current):+ if (+ os.path.basename(current).lower() == "workspace"+ and os.path.basename(os.path.dirname(current)).lower() == "agent"+ ):+ old_dir = Path(current)+ if old_dir.exists():+ # 旧目录还在(迁移未执行/未完成),不干预+ return raw+ new_dir = old_dir.parent / "jiuwenclaw_workspace"+ if not new_dir.is_dir():+ return raw+ tail = os.path.relpath(normalized, current)+ if tail == ".":+ return str(new_dir)+ return os.path.join(str(new_dir), tail)+ current = os.path.dirname(current)+ return raw++def validate_project_dir(path: str, *, default: Path | None = None) -> Path:"""Normalize ``project_dir``; create missing dirs; fall back on failure."""fallback = default if default is not None else get_agent_workspace_dir().resolve()- raw = (path or "").strip()+ raw = _remap_legacy_workspace_prefix((path or "").strip())if not raw:return fallbacktry:@@ -521,7 +575,7 @@ def get_resolved_project_dir(Lookup order:1. ``{sessions_root}/{session_id}/metadata.json`` when ``sessions_root`` given2. Global ``get_agent_sessions_dir()`` (where dig-stable chat sync writes today)- 3. ``default`` (typically tenant ``…/agent/workspace``), else ``get_agent_workspace_dir()``+ 3. ``default`` (typically tenant ``…/agent/jiuwenclaw_workspace``), else ``get_agent_workspace_dir()``Does not write defaults back into metadata (writers stay on chat sync path)."""diff --git a/jiuwenswarm/server/runtime/skill/skill_manager.py b/jiuwenswarm/server/runtime/skill/skill_manager.pyindex 5e6fccf5ea..0168417414 100644--- a/jiuwenswarm/server/runtime/skill/skill_manager.py+++ b/jiuwenswarm/server/runtime/skill/skill_manager.py@@ -4669,7 +4669,7 @@ class SkillManager:@staticmethoddef _generate_agent_data_for_workspace(workspace_root: Path) -> None:- """Generate agent/workspace/agent-data.json from agent tree."""+ """Generate agent/jiuwenclaw_workspace/agent-data.json from agent tree."""agent_root = workspace_root.resolve()output_path = (agent_root / "agent-data.json").resolve()root_folder_key = "__root__"diff --git a/jiuwenswarm/server/runtime/skill/skilldev/DESIGN.md b/jiuwenswarm/server/runtime/skill/skilldev/DESIGN.mdindex 6be88da4d6..c34b904b10 100644--- a/jiuwenswarm/server/runtime/skill/skilldev/DESIGN.md+++ b/jiuwenswarm/server/runtime/skill/skilldev/DESIGN.md@@ -496,7 +496,7 @@ DescOptimizeIteration # 描述优化的单轮迭代结果**存储路径**:```-~/.jiuwenswarm/agent/workspace/skilldev/{task_id}/state.json+~/.jiuwenswarm/agent/jiuwenclaw_workspace/skilldev/{task_id}/state.json```**核心接口**:@@ -515,7 +515,7 @@ store.list_tasks() # 列出所有有效 task_id**目录结构**:```-~/.jiuwenswarm/agent/workspace/skilldev/{task_id}/+~/.jiuwenswarm/agent/jiuwenclaw_workspace/skilldev/{task_id}/├── state.json ← StateStore 的 checkpoint 文件├── resources/ ← 上传的资源文件(解压后的原始内容)├── skill/ ← 生成的 Skill 目录(Agent 的写入区)@@ -684,7 +684,7 @@ class MyStageHandler(StageHandler):### 决策五:工作区路径统一**Why**:SkillDev 的任务目录必须在 JiuWenSwarm 的统一工作区下,避免数据散落在系统各处。-**约定**:`~/.jiuwenswarm/agent/workspace/skilldev/{task_id}/`,由 `get_workspace_dir() / "skilldev"` 构造。+**约定**:`~/.jiuwenswarm/agent/jiuwenclaw_workspace/skilldev/{task_id}/`,由 `get_workspace_dir() / "skilldev"` 构造。---diff --git a/jiuwenswarm/server/runtime/skill/skilldev/store.py b/jiuwenswarm/server/runtime/skill/skilldev/store.pyindex 714583d0b7..cb58083726 100644--- a/jiuwenswarm/server/runtime/skill/skilldev/store.py+++ b/jiuwenswarm/server/runtime/skill/skilldev/store.py@@ -30,7 +30,7 @@ class StateStore:"""Args:base_dir: SkillDev 工作区根目录,约定为 get_workspace_dir() / "skilldev"- 即 ~/.jiuwenswarm/agent/workspace/skilldev/+ 即 ~/.jiuwenswarm/agent/jiuwenclaw_workspace/skilldev/"""self._base_dir = base_dirdiff --git a/jiuwenswarm/server/runtime/skill/skilldev/workspace.py b/jiuwenswarm/server/runtime/skill/skilldev/workspace.pyindex e87d538e8b..758fe67824 100644--- a/jiuwenswarm/server/runtime/skill/skilldev/workspace.py+++ b/jiuwenswarm/server/runtime/skill/skilldev/workspace.py@@ -5,7 +5,7 @@职责:提供每个 task_id 的隔离工作区目录,并维护标准目录结构。目录结构(单机本地模式):- ~/.jiuwenswarm/agent/workspace/skilldev/{task_id}/+ ~/.jiuwenswarm/agent/jiuwenclaw_workspace/skilldev/{task_id}/├── state.json ← StateStore checkpoint├── resources/ ← 上传的资源文件(解压后)├── skill/ ← 生成的 skill 目录@@ -39,7 +39,7 @@ class WorkspaceProvider:"""Args:base_dir: SkillDev 工作区根目录,约定为 get_workspace_dir() / "skilldev"- 即 ~/.jiuwenswarm/agent/workspace/skilldev/+ 即 ~/.jiuwenswarm/agent/jiuwenclaw_workspace/skilldev/"""self._base_dir = base_dirdiff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/pipeline_init.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/pipeline_init.pyindex df40b29abf..19a243932e 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/pipeline_init.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/pipeline_init.py@@ -176,7 +176,7 @@ def _parse_cli_path(output: str) -> str:def _normalize_ppt_session_parent(path: Path) -> Path:"""PPT 时间戳目录的父路径:智能体工作空间本身,不再套一层 workspace。- 智能体工作空间是 ``.../agent/workspace``(部分环境为 ``.../agent/jiuwenclaw_workspace``)。+ 智能体工作空间是 ``.../agent/jiuwenclaw_workspace``(历史布局为 ``.../agent/workspace``)。历史兜底 ``{cwd}/workspace`` 会在工作空间已叫 workspace 时变成``.../agent/workspace/workspace``。"""diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.pyindex c59424b478..41e3a056c1 100644--- a/tests/agents/swarm/test_swarm_assembly.py+++ b/tests/agents/swarm/test_swarm_assembly.py@@ -338,7 +338,7 @@ async def test_team_skill_storage_policy_rail_resolves_and_injects_paths(tmp_patits identity, so this rail must not carry it in any lane."""register_swarm_providers()- global_skills_dir = str(tmp_path / "agent" / "workspace" / "skills")+ global_skills_dir = str(tmp_path / "agent" / "jiuwenclaw_workspace" / "skills")team_ws_root = str(tmp_path / ".agent_teams" / "unit" / "team-workspace")team_skills_dir = str(tmp_path / ".agent_teams" / "unit" / "team-workspace" / "skills")member_workspace_root = str(@@ -385,7 +385,7 @@ async def test_team_shared_skill_link_refresh_rail_resolves_and_refreshes() -> None:"""The shared skill link refresh rail should refresh after global skill writes."""register_swarm_providers()- global_skills_dir = tmp_path / "agent" / "workspace" / "skills"+ global_skills_dir = tmp_path / "agent" / "jiuwenclaw_workspace" / "skills"skill_dir = global_skills_dir / "new-skill"skill_dir.mkdir(parents=True)skill_file = skill_dir / "SKILL.md"diff --git a/tests/system_tests/conftest.py b/tests/system_tests/conftest.pyindex ec0caa8d5c..8e80957ade 100644--- a/tests/system_tests/conftest.py+++ b/tests/system_tests/conftest.py@@ -168,8 +168,8 @@ def verify_workspace_structure():workspace_dir / "agent" / "skills",workspace_dir / "agent" / "memory",workspace_dir / "agent" / "sessions",- workspace_dir / "agent" / "workspace",- workspace_dir / "agent" / "workspace" / "projects",+ workspace_dir / "agent" / "jiuwenclaw_workspace",+ workspace_dir / "agent" / "jiuwenclaw_workspace" / "projects",workspace_dir / "agent" / ".checkpoint",workspace_dir / "agent" / ".logs",]diff --git a/tests/system_tests/test_system_prompt_live_capture.py b/tests/system_tests/test_system_prompt_live_capture.pyindex b82a50b566..52f4e25ff7 100644--- a/tests/system_tests/test_system_prompt_live_capture.py+++ b/tests/system_tests/test_system_prompt_live_capture.py@@ -70,7 +70,7 @@ def _sync_prompt_workspace_templates(language: str) -> None:if not str(home_dir).startswith("/tmp/"):return- workspace_dir = home_dir / ".jiuwenswarm" / "agent" / "workspace"+ workspace_dir = home_dir / ".jiuwenswarm" / "agent" / "jiuwenclaw_workspace"if not workspace_dir.exists():returndiff --git a/tests/unit_tests/agentserver/test_rail_manager_scope.py b/tests/unit_tests/agentserver/test_rail_manager_scope.pyindex 5183d790b0..0331110edd 100644--- a/tests/unit_tests/agentserver/test_rail_manager_scope.py+++ b/tests/unit_tests/agentserver/test_rail_manager_scope.py@@ -54,8 +54,8 @@ def test_rail_manager_pool_isolates_tenants(monkeypatch, tmp_path):mgr_b = get_rail_manager(scope_b)assert mgr_a is not mgr_b- assert mgr_a.extensions_dir == tmp_path / "tenant-a" / "agent" / "workspace" / "extensions"- assert mgr_b.extensions_dir == tmp_path / "tenant-b" / "agent" / "workspace" / "extensions"+ assert mgr_a.extensions_dir == tmp_path / "tenant-a" / "agent" / "jiuwenclaw_workspace" / "extensions"+ assert mgr_b.extensions_dir == tmp_path / "tenant-b" / "agent" / "jiuwenclaw_workspace" / "extensions"assert get_rail_manager(scope_a) is mgr_aassert get_rail_manager(diff --git a/tests/unit_tests/agentserver/test_skill_prebuilt_guards.py b/tests/unit_tests/agentserver/test_skill_prebuilt_guards.pyindex 737004b2ed..3a9e734b11 100644--- a/tests/unit_tests/agentserver/test_skill_prebuilt_guards.py+++ b/tests/unit_tests/agentserver/test_skill_prebuilt_guards.py@@ -45,7 +45,7 @@ def test_tenant_workspace_defaults_without_key() -> None:clear_tenant_bindings()path = get_tenant_agent_workspace_dir()- assert path.name == "workspace"+ assert path.name == "jiuwenclaw_workspace"# 个人版固定 service_default/agent_default;未设 enterprise 时走该路径。assert "service_default" in str(path)assert "agent_default" in str(path)diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pyindex 60170be081..b157b17a0e 100644--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -1237,7 +1237,7 @@ async def test_runtime_rail_multi_tenant_workspace_dirs(monkeypatch):monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")builder = SystemPromptBuilder(language="cn")- workspace_root = Path("/tmp/test_jiuwenswarm/workspace_abc/agent/workspace")+ workspace_root = Path("/tmp/test_jiuwenswarm/workspace_abc/agent/jiuwenclaw_workspace")runtime_rail = RuntimePromptRail(language="cn",channel="web",@@ -1290,7 +1290,7 @@ async def test_runtime_rail_single_tenant_workspace_dirs():) as mock_agent_ws,):mock_user_ws.return_value = Path("/home/user/.jiuwenswarm")- mock_agent_ws.return_value = Path("/home/user/.jiuwenswarm/agent/workspace")+ mock_agent_ws.return_value = Path("/home/user/.jiuwenswarm/agent/jiuwenclaw_workspace")ctx = AgentCallbackContext(agent=None, inputs=None, session=None)await runtime_rail.before_model_call(ctx)@@ -1304,7 +1304,7 @@ async def test_runtime_rail_single_tenant_workspace_dirs():# 验证完整绝对路径(兼容 Windows/Linux 分隔符)expected_config = "/home/user/.jiuwenswarm/config"- expected_workspace = "/home/user/.jiuwenswarm/agent/workspace"+ expected_workspace = "/home/user/.jiuwenswarm/agent/jiuwenclaw_workspace"expected_config_win = expected_config.replace("/", "\\")expected_workspace_win = expected_workspace.replace("/", "\\")assert (diff --git a/tests/unit_tests/channel/test_dingtalk_detect_workspace_files.py b/tests/unit_tests/channel/test_dingtalk_detect_workspace_files.pyindex 401fe4b46a..ab46816a70 100644--- a/tests/unit_tests/channel/test_dingtalk_detect_workspace_files.py+++ b/tests/unit_tests/channel/test_dingtalk_detect_workspace_files.py@@ -48,7 +48,7 @@ def _write_session_project_dir(def test_detect_abs_path_under_tenant_workspace(monkeypatch, tmp_path: Path):ch = _make_channel()patch_multi_tenant_workspace_dirs(monkeypatch, tmp_path)- ws = _tenant_agent_root(tmp_path, "office", "bot") / "workspace"+ ws = _tenant_agent_root(tmp_path, "office", "bot") / "jiuwenclaw_workspace"ws.mkdir(parents=True)target = ws / "report.docx"target.write_bytes(b"docx")@@ -74,7 +74,7 @@ def test_detect_quoted_filename_uses_session_project_dir(monkeypatch, tmp_path:sessions = _tenant_agent_root(tmp_path, "default", "office") / "sessions"_write_session_project_dir(sessions, "sess_proj", project)- ws = _tenant_agent_root(tmp_path, "default", "office") / "workspace"+ ws = _tenant_agent_root(tmp_path, "default", "office") / "jiuwenclaw_workspace"ws.mkdir(parents=True)found = ch._detect_workspace_files(@@ -92,7 +92,7 @@ def test_detect_falls_back_to_tenant_workspace_when_no_project_dir():ch = _make_channel()patch_multi_tenant_workspace_dirs(monkeypatch, tmp_path)- ws = _tenant_agent_root(tmp_path, "default", "office") / "workspace"+ ws = _tenant_agent_root(tmp_path, "default", "office") / "jiuwenclaw_workspace"ws.mkdir(parents=True)target = ws / "notes.pdf"target.write_bytes(b"%PDF")@@ -110,10 +110,10 @@ def test_detect_falls_back_to_tenant_workspace_when_no_project_dir(def test_detect_does_not_use_other_tenant_workspace(monkeypatch, tmp_path: Path):ch = _make_channel()patch_multi_tenant_workspace_dirs(monkeypatch, tmp_path)- other = _tenant_agent_root(tmp_path, "default", "other") / "workspace"+ other = _tenant_agent_root(tmp_path, "default", "other") / "jiuwenclaw_workspace"other.mkdir(parents=True)(other / "secret.docx").write_bytes(b"x")- mine = _tenant_agent_root(tmp_path, "default", "office") / "workspace"+ mine = _tenant_agent_root(tmp_path, "default", "office") / "jiuwenclaw_workspace"mine.mkdir(parents=True)found = ch._detect_workspace_files(diff --git a/tests/unit_tests/channel/test_feishu_detect_workspace_files.py b/tests/unit_tests/channel/test_feishu_detect_workspace_files.pyindex d955929b98..6e50a0205d 100644--- a/tests/unit_tests/channel/test_feishu_detect_workspace_files.py+++ b/tests/unit_tests/channel/test_feishu_detect_workspace_files.py@@ -56,7 +56,7 @@ def _write_session_project_dir(def test_detect_abs_path_under_tenant_workspace(monkeypatch, tmp_path: Path):ch = _make_channel()patch_multi_tenant_workspace_dirs(monkeypatch, tmp_path)- ws = _tenant_agent_root(tmp_path, "office", "bot") / "workspace"+ ws = _tenant_agent_root(tmp_path, "office", "bot") / "jiuwenclaw_workspace"ws.mkdir(parents=True)target = ws / "report.docx"target.write_bytes(b"docx")@@ -83,7 +83,7 @@ def test_detect_quoted_filename_uses_session_project_dir(monkeypatch, tmp_path:_write_session_project_dir(sessions, "sess_proj", project)# Default tenant workspace exists but does NOT contain notes.pdf- ws = _tenant_agent_root(tmp_path, "default", "office") / "workspace"+ ws = _tenant_agent_root(tmp_path, "default", "office") / "jiuwenclaw_workspace"ws.mkdir(parents=True)found = ch._detect_workspace_files(@@ -101,7 +101,7 @@ def test_detect_falls_back_to_tenant_workspace_when_no_project_dir():ch = _make_channel()patch_multi_tenant_workspace_dirs(monkeypatch, tmp_path)- ws = _tenant_agent_root(tmp_path, "default", "office") / "workspace"+ ws = _tenant_agent_root(tmp_path, "default", "office") / "jiuwenclaw_workspace"ws.mkdir(parents=True)target = ws / "notes.pdf"target.write_bytes(b"%PDF")@@ -119,10 +119,10 @@ def test_detect_falls_back_to_tenant_workspace_when_no_project_dir(def test_detect_does_not_use_other_tenant_workspace(monkeypatch, tmp_path: Path):ch = _make_channel()patch_multi_tenant_workspace_dirs(monkeypatch, tmp_path)- other = _tenant_agent_root(tmp_path, "default", "other") / "workspace"+ other = _tenant_agent_root(tmp_path, "default", "other") / "jiuwenclaw_workspace"other.mkdir(parents=True)(other / "secret.docx").write_bytes(b"x")- mine = _tenant_agent_root(tmp_path, "default", "office") / "workspace"+ mine = _tenant_agent_root(tmp_path, "default", "office") / "jiuwenclaw_workspace"mine.mkdir(parents=True)found = ch._detect_workspace_files(diff --git a/tests/unit_tests/symphony/test_config.py b/tests/unit_tests/symphony/test_config.pyindex 488ce1e3e8..93a26e6180 100644--- a/tests/unit_tests/symphony/test_config.py+++ b/tests/unit_tests/symphony/test_config.py@@ -7,14 +7,14 @@ def test_symphony_config_defaults_paths(monkeypatch, tmp_path):monkeypatch.setattr(symphony_config,"get_agent_workspace_dir",- lambda: tmp_path / "agent" / "workspace",+ lambda: tmp_path / "agent" / "jiuwenclaw_workspace",)cfg = symphony_config.symphony_config_from_dict({})- assert cfg.paths.skills_root == (tmp_path / "agent" / "workspace" / "skills").resolve()+ assert cfg.paths.skills_root == (tmp_path / "agent" / "jiuwenclaw_workspace" / "skills").resolve()assert cfg.paths.score_dir == (- tmp_path / "agent" / "workspace" / "symphony" / "score"+ tmp_path / "agent" / "jiuwenclaw_workspace" / "symphony" / "score").resolve()assert cfg.fingerprint.scan.max_depth is Noneassert cfg.fingerprint.extraction.body_limit is Nonediff --git a/tests/unit_tests/test_file_transfer_config.py b/tests/unit_tests/test_file_transfer_config.pyindex 5692d35fcd..4beb4512cb 100644--- a/tests/unit_tests/test_file_transfer_config.py+++ b/tests/unit_tests/test_file_transfer_config.py@@ -19,7 +19,7 @@ def test_file_transfer_config_default_values():assert config.chunk_size == 65536assert config.max_file_size == 104857600assert config.transfer_timeout == 300- assert config.received_files_dir == "agent/workspace/received_files"+ assert config.received_files_dir == "agent/jiuwenclaw_workspace/received_files"assert config.cleanup_interval == 3600assert config.cleanup_age == 86400assert config.max_concurrent_transfers == 5diff --git a/tests/unit_tests/test_project_handlers.py b/tests/unit_tests/test_project_handlers.pyindex d93ebc9566..1a49dadfe1 100644--- a/tests/unit_tests/test_project_handlers.py+++ b/tests/unit_tests/test_project_handlers.py@@ -782,7 +782,7 @@ class TestEmptyPathProject:assert resp["payload"]["project_id"].startswith("proj_")# work_mode 改造后默认工作区按 work_mode 分桶:Web 通道默认 work 模式# → workspace/work/{name}- expected_path = str(get_agent_root_dir() / "workspace" / "work" / "空项目A")+ expected_path = str(get_agent_root_dir() / "jiuwenclaw_workspace" / "work" / "空项目A")assert resp["payload"]["project_dir"] == expected_pathassert os.path.isdir(expected_path)assert resp["payload"]["restored"] is Falsediff --git a/tests/unit_tests/test_session_metadata.py b/tests/unit_tests/test_session_metadata.pyindex 043f25f2a7..a1da412155 100644--- a/tests/unit_tests/test_session_metadata.py+++ b/tests/unit_tests/test_session_metadata.py@@ -2088,6 +2088,133 @@ class TestLazyMigrationOnRead:assert data["project_id"] == ""+class TestLegacyWorkspacePrefixRemap:+ """agent/workspace → agent/jiuwenclaw_workspace 改名后的旧路径重映射。++ 迁移函数会重写 projects.json / metadata.json,但读路径兜底重映射+ 保证遗漏记录(备份恢复、外部写入等)不会在旧路径上 mkdir 复活僵尸目录。+ """++ @staticmethod+ def test_remap_when_old_gone_and_new_exists(tmp_path):+ from jiuwenswarm.server.runtime.session.session_metadata import (+ _remap_legacy_workspace_prefix,+ )++ agent_root = tmp_path / "service_default" / "agent_default" / "agent"+ new_ws = agent_root / "jiuwenclaw_workspace"+ new_ws.mkdir(parents=True)+ old = agent_root / "workspace"++ old_str = str(old / "work" / "demo")+ remapped = _remap_legacy_workspace_prefix(old_str)+ assert remapped == str(new_ws / "work" / "demo")++ # 路径恰好等于旧工作区本身+ assert _remap_legacy_workspace_prefix(str(old)) == str(new_ws)++ @staticmethod+ def test_no_remap_when_old_dir_still_exists(tmp_path):+ """旧目录还在(迁移未执行)时不干预,避免在迁移前改写路径。"""+ from jiuwenswarm.server.runtime.session.session_metadata import (+ _remap_legacy_workspace_prefix,+ )++ agent_root = tmp_path / "agent"+ old = agent_root / "workspace"+ old.mkdir(parents=True)++ assert _remap_legacy_workspace_prefix(str(old / "work" / "demo")) == str(+ old / "work" / "demo"+ )++ @staticmethod+ def test_no_remap_when_new_dir_missing(tmp_path):+ """新目录不存在(全新环境/无关路径)时保持原样。"""+ from jiuwenswarm.server.runtime.session.session_metadata import (+ _remap_legacy_workspace_prefix,+ )++ agent_root = tmp_path / "agent"+ old = agent_root / "workspace"++ assert _remap_legacy_workspace_prefix(str(old / "work" / "demo")) == str(+ old / "work" / "demo"+ )++ @staticmethod+ def test_unrelated_path_untouched(tmp_path):+ """不含 /agent/workspace 锚点的路径原样返回。"""+ from jiuwenswarm.server.runtime.session.session_metadata import (+ _remap_legacy_workspace_prefix,+ )++ for raw in ("", "E:\\repos\\demo", str(tmp_path / "workspace" / "a")):+ assert _remap_legacy_workspace_prefix(raw) == raw++ @staticmethod+ def test_validate_project_dir_uses_remapped_path(tmp_path, monkeypatch):+ """旧前缀的 project_dir 经 validate_project_dir 后落到新目录,+ 不在旧路径上 mkdir。"""+ agent_root = tmp_path / "service_default" / "agent_default" / "agent"+ new_ws = agent_root / "jiuwenclaw_workspace"+ new_ws.mkdir(parents=True)+ old = agent_root / "workspace"++ from jiuwenswarm.server.runtime.session.session_metadata import (+ validate_project_dir,+ )++ result = validate_project_dir(+ str(old / "work" / "demo"), default=new_ws+ )+ assert result == (new_ws / "work" / "demo").resolve()+ # 旧目录未被复活+ assert not old.exists()++ @staticmethod+ def test_read_metadata_remaps_and_writes_back(tmp_path, monkeypatch):+ """读路径惰性迁移:metadata 中旧前缀被重映射并异步写盘。++ 直接调用 _apply_metadata_defaults_with_inference 绕开+ sanitize_session_id 的导入链(其依赖 openjiuwen 子模块,+ 在部分测试环境缺失,与 TestLazyMigrationOnRead 整类的既有+ 环境性 ERROR 相同,非本用例逻辑问题)。+ """+ agent_root = tmp_path / "service_default" / "agent_default" / "agent"+ new_ws = agent_root / "jiuwenclaw_workspace"+ new_ws.mkdir(parents=True)+ old = agent_root / "workspace"+ old_project = str(old / "work" / "demo")++ sdir = agent_root / "sessions" / "s_legacy_ws"+ sdir.mkdir(parents=True)+ (sdir / "metadata.json").write_text(+ json.dumps(+ {+ "session_id": "s_legacy_ws",+ "project_dir": old_project,+ "channel_metadata": {"cwd": old_project, "project_dir": old_project},+ }+ ),+ encoding="utf-8",+ )++ from jiuwenswarm.server.runtime.session.session_metadata import (+ _apply_metadata_defaults_with_inference,+ )++ metadata = json.loads((sdir / "metadata.json").read_text(encoding="utf-8"))+ result = _apply_metadata_defaults_with_inference(+ "s_legacy_ws", metadata, session_dir=sdir, enable_writeback=False+ )++ expected = str(new_ws / "work" / "demo")+ assert result["project_dir"] == expected+ assert result["channel_metadata"]["cwd"] == expected+ assert result["channel_metadata"]["project_dir"] == expected++# ===========================================================================# set_session_pinned —— 跨进程同步落盘(sync_write)回归# ===========================================================================diff --git a/tests/unit_tests/test_utils.py b/tests/unit_tests/test_utils.pyindex da05513d36..4557f2f6b7 100644--- a/tests/unit_tests/test_utils.py+++ b/tests/unit_tests/test_utils.py@@ -4,6 +4,7 @@import importlibimport os+import shutilimport sysfrom pathlib import Pathfrom unittest.mock import patch@@ -452,7 +453,7 @@ class TestHardcodedPathsPhase2:/ "service_default"/ "agent_default"/ "agent"- / "workspace"+ / "jiuwenclaw_workspace"/ "task-data.json")actual_path = Path(_get_task_data_path())@@ -478,7 +479,7 @@ class TestHardcodedPathsPhase2:/ "service_default"/ "agent_default"/ "agent"- / "workspace"+ / "jiuwenclaw_workspace"/ "USER.md")actual_path = get_deepagent_user_md_path()@@ -534,7 +535,7 @@ class TestAdditionalHardcodedPaths:os.environ["JIUWENSWARM_EDITION"] = "enterprise"try:workspace = get_multi_tenant_user_workspace_dir(scope.workspace_key)- expected_path = workspace / "agent" / "workspace" / "extensions"+ expected_path = workspace / "agent" / "jiuwenclaw_workspace" / "extensions"rail_manager = get_rail_manager(scope)extensions_dir = rail_manager.extensions_dir@@ -574,10 +575,237 @@ class TestAdditionalHardcodedPaths:/ "service_default"/ "agent_default"/ "agent"- / "workspace"+ / "jiuwenclaw_workspace"/ "interactions")actual_path = get_interactions_dir()assert str(actual_path.resolve()) == str(expected_path.resolve()), \f"Expected: {expected_path.resolve()}, Got: {actual_path.resolve()}"+++class TestWorkspaceToJiuwenclawWorkspaceMigration:+ """Migrate runtime agent workspace: agent/workspace -> agent/jiuwenclaw_workspace."""++ @staticmethod+ def _make_old_layout(root: Path, tenant: str = "personal") -> Path:+ if tenant == "personal":+ agent_root = root / "service_default" / "agent_default" / "agent"+ else:+ agent_root = root / "workspace_abc" / "agent"+ old_ws = agent_root / "workspace"+ (old_ws / "skills").mkdir(parents=True)+ (old_ws / "skills" / "demo.md").write_text("skill", encoding="utf-8")+ (old_ws / "HEARTBEAT.md").write_text("heartbeat", encoding="utf-8")+ return old_ws++ def test_rename_personal_tenant(self, tmp_path: Path):+ old_ws = self._make_old_layout(tmp_path, "personal")+ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path)++ new_ws = tmp_path / "service_default" / "agent_default" / "agent" / "jiuwenclaw_workspace"+ assert not old_ws.exists()+ assert (new_ws / "HEARTBEAT.md").read_text(encoding="utf-8") == "heartbeat"+ assert (new_ws / "skills" / "demo.md").exists()++ def test_rename_enterprise_tenant(self, tmp_path: Path):+ old_ws = self._make_old_layout(tmp_path, "enterprise")+ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path)++ new_ws = tmp_path / "workspace_abc" / "agent" / "jiuwenclaw_workspace"+ assert not old_ws.exists()+ assert (new_ws / "HEARTBEAT.md").exists()++ def test_merge_when_both_exist(self, tmp_path: Path):+ old_ws = self._make_old_layout(tmp_path, "personal")+ new_ws = tmp_path / "service_default" / "agent_default" / "agent" / "jiuwenclaw_workspace"+ (new_ws / "memory").mkdir(parents=True)+ (new_ws / "memory" / "MEMORY.md").write_text("memory", encoding="utf-8")++ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path)++ assert not old_ws.exists()+ # merged content from both sides+ assert (new_ws / "memory" / "MEMORY.md").read_text(encoding="utf-8") == "memory"+ assert (new_ws / "HEARTBEAT.md").read_text(encoding="utf-8") == "heartbeat"+ assert (new_ws / "skills" / "demo.md").exists()++ def test_merge_top_level_conflict(self, tmp_path: Path):+ old_ws = self._make_old_layout(tmp_path, "personal")+ agent_root = tmp_path / "service_default" / "agent_default" / "agent"+ new_ws = agent_root / "jiuwenclaw_workspace"+ new_ws.mkdir(parents=True)+ (new_ws / "USER.md").write_text("new-side", encoding="utf-8")+ (old_ws / "USER.md").write_text("old-side", encoding="utf-8")++ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path)++ assert not old_ws.exists()+ # New side wins the conflict...+ assert (new_ws / "USER.md").read_text(encoding="utf-8") == "new-side"+ # ...and the old-side content is preserved in a backup dir, not lost.+ # Backup lives under agent/ (hidden sibling), not inside the workspace+ # where it would pollute the file tree exposed to users and the Agent.+ backups = list(agent_root.glob(".migration-backup-*/USER.md"))+ assert len(backups) == 1+ assert backups[0].read_text(encoding="utf-8") == "old-side"++ def test_merge_nested_conflict(self, tmp_path: Path):+ old_ws = self._make_old_layout(tmp_path, "personal")+ agent_root = tmp_path / "service_default" / "agent_default" / "agent"+ new_ws = agent_root / "jiuwenclaw_workspace"+ (new_ws / "memory").mkdir(parents=True)+ (new_ws / "memory" / "MEMORY.md").write_text("new-side", encoding="utf-8")+ (old_ws / "memory").mkdir()+ (old_ws / "memory" / "MEMORY.md").write_text("old-side", encoding="utf-8")+ # old-side-only nested file must still be merged in+ (old_ws / "memory" / "2026-09-07.md").write_text("daily", encoding="utf-8")++ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path)++ assert not old_ws.exists()+ # Same priority direction as top-level: new side wins inside directories+ assert (new_ws / "memory" / "MEMORY.md").read_text(encoding="utf-8") == "new-side"+ assert (new_ws / "memory" / "2026-09-07.md").read_text(encoding="utf-8") == "daily"+ # Old-side conflicting file backed up, not overwritten/lost+ backups = list(agent_root.glob(".migration-backup-*/memory/MEMORY.md"))+ assert len(backups) == 1+ assert backups[0].read_text(encoding="utf-8") == "old-side"++ def test_noop_when_no_legacy_layout(self, tmp_path: Path):+ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path)+ assert not (tmp_path / "jiuwenclaw_workspace").exists()++ def test_legacy_pre_tenant_layout(self, tmp_path: Path):+ old_ws = tmp_path / "agent" / "workspace"+ old_ws.mkdir(parents=True)+ (old_ws / "todo").mkdir()+ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path)+ assert (tmp_path / "agent" / "jiuwenclaw_workspace" / "todo").exists()++ @staticmethod+ def _write_legacy_metadata(agent_root: Path, old_ws: Path) -> None:+ """Simulate pre-migration on-disk state: projects.json + session metadata+ whose project_dir strings point at the OLD absolute workspace path."""+ import json as _json++ (agent_root / "projects.json").write_text(+ _json.dumps(+ {+ "version": 1,+ "projects": [+ {+ "project_id": "p1",+ "name": "demo",+ "project_dir": str(old_ws / "work" / "demo"),+ }+ ],+ }+ ),+ encoding="utf-8",+ )+ sess_dir = agent_root / "sessions" / "sess-1"+ sess_dir.mkdir(parents=True)+ (sess_dir / "metadata.json").write_text(+ _json.dumps(+ {+ "session_id": "sess-1",+ "project_dir": str(old_ws / "work" / "demo"),+ "channel_metadata": {+ "cwd": str(old_ws / "work" / "demo"),+ "project_dir": str(old_ws / "work" / "demo"),+ },+ }+ ),+ encoding="utf-8",+ )++ def test_migration_rewrites_persisted_project_dir(self, tmp_path: Path):+ """Regression: persisted project_dir must follow the renamed directory.++ Otherwise validate_project_dir re-creates the old path (zombie dir),+ the next restart merges it away again, and files written in between+ become invisible to the session.+ """+ import json as _json++ old_ws = self._make_old_layout(tmp_path, "personal")+ agent_root = tmp_path / "service_default" / "agent_default" / "agent"+ self._write_legacy_metadata(agent_root, old_ws)++ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path)++ new_ws = agent_root / "jiuwenclaw_workspace"+ new_project_dir = str(new_ws / "work" / "demo")++ projects = _json.loads(+ (agent_root / "projects.json").read_text(encoding="utf-8")+ )+ assert projects["projects"][0]["project_dir"] == new_project_dir++ meta = _json.loads(+ (agent_root / "sessions" / "sess-1" / "metadata.json").read_text(+ encoding="utf-8"+ )+ )+ assert meta["project_dir"] == new_project_dir+ assert meta["channel_metadata"]["cwd"] == new_project_dir+ assert meta["channel_metadata"]["project_dir"] == new_project_dir++ def test_migration_rewrites_metadata_on_merge_too(self, tmp_path: Path):+ """Merge branch (both dirs exist) must also rewrite persisted paths."""+ import json as _json++ old_ws = self._make_old_layout(tmp_path, "personal")+ agent_root = tmp_path / "service_default" / "agent_default" / "agent"+ (agent_root / "jiuwenclaw_workspace").mkdir(parents=True)+ self._write_legacy_metadata(agent_root, old_ws)++ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path)++ projects = _json.loads(+ (agent_root / "projects.json").read_text(encoding="utf-8")+ )+ new_ws = agent_root / "jiuwenclaw_workspace"+ assert projects["projects"][0]["project_dir"] == str(new_ws / "work" / "demo")++ def test_metadata_rewrite_idempotent(self, tmp_path: Path):+ """Re-running migration (e.g. crash-restart loop) must not corrupt metadata."""+ import json as _json++ old_ws = self._make_old_layout(tmp_path, "personal")+ agent_root = tmp_path / "service_default" / "agent_default" / "agent"+ self._write_legacy_metadata(agent_root, old_ws)++ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path)+ # Second run: old dir gone; metadata rewrite must be a no-op, not a rewrite+ mtime_first = (agent_root / "projects.json").stat().st_mtime_ns+ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path)++ new_ws = agent_root / "jiuwenclaw_workspace"+ projects = _json.loads(+ (agent_root / "projects.json").read_text(encoding="utf-8")+ )+ assert projects["projects"][0]["project_dir"] == str(new_ws / "work" / "demo")+ assert (agent_root / "projects.json").stat().st_mtime_ns == mtime_first++ def test_concurrent_migration_missing_old_dir_no_crash(self, tmp_path: Path):+ """Simulate another process finishing the move first: FileNotFoundError+ from move/rmtree must not crash startup; metadata still rewritten."""+ import json as _json++ old_ws = self._make_old_layout(tmp_path, "personal")+ agent_root = tmp_path / "service_default" / "agent_default" / "agent"+ self._write_legacy_metadata(agent_root, old_ws)++ # Another "process" migrates and leaves no old dir behind+ (agent_root / "jiuwenclaw_workspace").mkdir(parents=True)+ shutil.rmtree(old_ws)++ utils._migrate_workspace_to_jiuwenclaw_workspace(tmp_path) # must not raise++ projects = _json.loads(+ (agent_root / "projects.json").read_text(encoding="utf-8")+ )+ new_ws = agent_root / "jiuwenclaw_workspace"+ assert projects["projects"][0]["project_dir"] == str(new_ws / "work" / "demo")diff --git a/tests/unit_tests/test_web_http_file_compat.py b/tests/unit_tests/test_web_http_file_compat.pyindex 6d23c9c46d..cbec3701ec 100644--- a/tests/unit_tests/test_web_http_file_compat.py+++ b/tests/unit_tests/test_web_http_file_compat.py@@ -26,7 +26,7 @@ from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel, WebCdef file_client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)agent_root = tmp_path / "agent"- workspace = agent_root / "workspace"+ workspace = agent_root / "jiuwenclaw_workspace"workspace.mkdir(parents=True)(workspace / "hello.md").write_text("# hi\n", encoding="utf-8")image_path = agent_root / "sessions" / "s1" / "uploads" / "image.png"@@ -53,19 +53,34 @@ def file_client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):def test_list_and_read_markdown(file_client):client, _roots, _img, _bytes = file_client- r = client.get("/file-api/list-files", params={"dir": "agent/workspace"})+ r = client.get("/file-api/list-files", params={"dir": "agent/jiuwenclaw_workspace"})assert r.status_code == 200names = {f["name"] for f in r.json()["files"]}assert "hello.md" in namesr = client.get("/file-api/file-content",- params={"path": "agent/workspace/hello.md", "encoding": "utf-8"},+ params={"path": "agent/jiuwenclaw_workspace/hello.md", "encoding": "utf-8"},)assert r.status_code == 200assert r.text.startswith("# hi")+def test_legacy_agent_data_path_returns_generated_content(file_client):+ """Old pre-rename path ``agent/workspace/agent-data.json`` must serve generated data."""+ client, roots, _img, _bytes = file_client+ assert not (roots.project_root / "agent" / "workspace").exists()++ r = client.get(+ "/file-api/file-content",+ params={"path": "agent/workspace/agent-data.json", "encoding": "utf-8"},+ )+ assert r.status_code == 200+ # generated at the new path and served from there+ assert (roots.workspace_root / "jiuwenclaw_workspace" / "agent-data.json").is_file()+ assert "hello.md" in r.text++def test_raw_file(file_client):client, roots, image_path, image_bytes = file_clientrel = str(image_path.relative_to(roots.project_root)).replace("\\", "/")@@ -82,9 +97,9 @@ def test_path_traversal_forbidden(file_client):def test_default_roots_allow_legacy_agent_workspace(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):- """Personal layout: ``agent/workspace`` under user workspace, not only multi-tenant agent root."""+ """Personal layout: ``agent/jiuwenclaw_workspace`` under user workspace, not only multi-tenant agent root."""user_root = tmp_path / "home" / ".jiuwenswarm"- agent_ws = user_root / "agent" / "workspace"+ agent_ws = user_root / "agent" / "jiuwenclaw_workspace"agent_ws.mkdir(parents=True)(agent_ws / "note.md").write_text("ok", encoding="utf-8")tenant_agent = user_root / "service_default" / "agent_default" / "agent"@@ -102,7 +117,7 @@ def test_default_roots_allow_legacy_agent_workspace(tmp_path: Path, monkeypatch:from jiuwenswarm.gateway.channel_manager.web.file_http import default_file_http_roots, list_filesroots = default_file_http_roots()- code, payload = list_files(roots, "agent/workspace")+ code, payload = list_files(roots, "agent/jiuwenclaw_workspace")assert code == 200assert any(f["name"] == "note.md" for f in payload["files"])