Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(tui):修改/memory交互

jingjinduoca4658a0fc1e
diff --git a/docs/en/AutoMemory.md b/docs/en/AutoMemory.md
index 617270ea9b..43b562df0c 100644
--- a/docs/en/AutoMemory.md
+++ b/docs/en/AutoMemory.md
@@ -16,24 +16,32 @@ Auto Memory is JiuwenSwarm's post-conversation memory extraction feature. After
### Config File
-Set `auto_memory_enabled` in `config.yaml`:
+The config key is mode-aware:
+
+- **agent mode**: global `auto_memory_enabled` (top-level in `config.yaml`);
+- **code mode**: `modes.code.memory.auto_coding_memory` (under the `modes.code.memory` section).
```yaml
-# Auto Memory: Automatically extract memories after conversation ends, stored per-project
+# agent mode — global toggle
auto_memory_enabled: true
+
+# code mode — per-mode toggle under modes.code.memory
+modes:
+ code:
+ memory:
+ auto_coding_memory: true
```
### TUI Command
-Toggle via `/memory` command in TUI terminal:
+Open the tabbed console via `/memory` command in TUI terminal:
```
-/memory # Enter memory management interface
-/memory toggle # Show all memory toggles
-/memory toggle auto_memory_enabled # Toggle auto memory switch
+/memory # Open memory management tabbed console
+/memory toggle # Switch to toggle tab
```
-In the interactive interface, select the `Auto-memory: on/off` option to toggle.
+The tabbed console provides 4 tabs: edit / status / toggle / open, with the **edit** tab selected by default. Interaction keys: ←/→ switch tabs, ↑/↓ move within the list, Enter execute the selected item, Ctrl+O toggle full path (edit/open tabs; resets to relative path when switching tabs), Esc close the console.
---
@@ -77,7 +85,7 @@ The system analyzes conversation content through a sub-Agent, extracting the fol
```mermaid
flowchart TD
- A[Conversation End] --> B{auto_memory_enabled?}
+ A[Conversation End] --> B{auto_memory enabled?}
B -->|No| C[Skip Extraction]
B -->|Yes| D[Create Extraction Sub-Agent]
D --> E[Analyze Conversation History]
@@ -92,7 +100,8 @@ flowchart TD
| Config Item | Description | Default Value |
|------------|-------------|---------------|
-| `auto_memory_enabled` | Whether to enable auto memory extraction | `false` |
+| `auto_memory_enabled` | Auto memory extraction toggle (agent mode, top-level) | `false` |
+| `modes.code.memory.auto_coding_memory` | Auto coding memory extraction toggle (code mode) | `false` |
---
@@ -100,20 +109,29 @@ flowchart TD
### `/memory` Command
-Enter `/memory` command in TUI to display memory management interface:
+Enter `/memory` command in TUI to open the memory management tabbed console (the **edit** tab is selected by default):
```
Memory
-Select a memory file to edit:
-
- Auto-memory: on [Press Enter to toggle]
- Project memory Checked in at ./JIUWENSWARM.md
- Local memory Saved in ./JIUWENSWARM.local.md
- User memory Saved in ~/.jiuwen/JIUWENSWARM.md
- Open auto-memory folder
+[edit] [status] [toggle] [open]
+ ↑
+ ←/→ switch tabs | ↑/↓ move list | Enter execute | Ctrl+O toggle full path (edit/open) | Esc close
+
+--- toggle tab ---
+Switches adapt to the current mode. Each row shows the key (padded), a ✓ on / ✗ off marker, and a Chinese description (separated by spaces, no ·):
+
+agent mode:
+ memory_enabled ✓ on 记忆功能总开关
+ memory_proactive ✓ on 对话中自动搜索和记录
+ memory_forbidden_enabled ✗ off 过滤敏感信息
+
+code mode:
+ memory_enabled ✓ on 记忆功能总开关
+ auto_coding_memory ✓ on 每轮对话后自动提取记忆(需总开关开启)
+ memory_forbidden_enabled ✗ off 过滤敏感信息
```
-Select the `Auto-memory: on/off` row and press Enter to toggle auto memory.
+The switches in the toggle tab adapt to the current mode (agent mode / code mode). Toggle the corresponding switch to enable/disable the respective memory feature.
---
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.md
index cacbf38789..1a5fc80b59 100644
--- a/docs/en/SlashCommands.md
+++ b/docs/en/SlashCommands.md
@@ -324,30 +324,58 @@ These commands are registered and parsed by the TUI, then forwarded as slash tex
### `/memory` (Memory Management)
- Alias: `/mem`.
-- Function: View and manage memory system status, memory files, toggle settings, and directory paths.
+- Function: View and manage memory system status, memory files, toggle settings, and directory paths via a tabbed console.
- Subcommands:
| Command | Description |
|---|---|
-| `/memory` or `/memory edit` | Interactively select and edit a memory file (lists available files when no path is given) |
-| `/memory list` | List all memory files (with size, line count, modification time) |
-| `/memory edit <path>` | Open the specified memory file for editing (via `$EDITOR`) |
-| `/memory status` | Show detailed memory system status |
-| `/memory toggle [key]` | Toggle memory system switches (lists togglable items when no key is given) |
-| `/memory open` | Show memory system directory paths |
-
+| `/memory` or `/memory edit` | Open the tabbed console and select the edit tab |
+| `/memory edit <path>` | Directly edit the specified memory file (via `$EDITOR`) |
+| `/memory status` | Open the tabbed console and select the status tab |
+| `/memory toggle` | Open the tabbed console and select the toggle tab |
+| `/memory toggle <key>` | Directly toggle the specified memory system switch |
+| `/memory open` | Open the tabbed console and select the open tab |
+
+- Tabbed console: The console has 4 tabs — edit / status / toggle / open. Interaction keys:
+ - `←`/`→` — Switch tabs;
+ - `↑`/`↓` — Navigate within the current tab;
+ - `Enter` — Execute the selected item;
+ - `Ctrl+O` — Toggle full path display (edit / open tabs); resets to default (relative path) when switching tabs;
+ - `Esc` — Close the console.
+- `edit` display contents:
+ - Lists memory files in priority order: Project memory (Checked in at `<path>`), Local memory (Saved in `<path>`), User memory (Saved in `<path>`), plus any rule files;
+ - `Enter` opens the selected file with `$EDITOR`.
- `status` display contents:
- - Current mode, storage engine, enabled status, proactive status, forbidden filter status;
- - Index status (FTS5, Vector, Cache), file count, chunk count;
- - Statistics for Project Memory, Coding Memory, Auto Memory, and External Memory.
-- `toggle` available keys:
- - `memory_enabled` — Master memory switch;
- - `memory_proactive` — Proactive memory switch;
- - `memory_forbidden_enabled` — Forbidden filter switch.
+ - Engine (format `builtin (local)`, combining the storage engine and storage mode);
+ - Switch row — mode-adaptive (mirrors the current mode's toggle set), shown as `✓ on` / `✗ off`:
+ - agent mode: `memory_enabled` (Memory), `memory_proactive` (Proactive memory), `memory_forbidden_enabled` (Forbidden filter);
+ - code mode: `memory_enabled` (Memory), `auto_coding_memory` (Auto coding memory), `memory_forbidden_enabled` (Forbidden filter).
+ - Runtime memory statistics — mode-adaptive: agent mode shows "Auto Memory" (files / chars / dir); code mode shows "Coding Memory" (files / chars / dir);
+ - Project Memory statistics (files / chars / project dir);
+ - External Memory (provider + enabled status), shown only if configured.
+- `toggle` display contents:
+ - Each row shows the toggle **key** (padded to equal width), a `✓ on` / `✗ off` status marker, and a Chinese description. Only the key is shown (no English label); columns are separated by spaces, not `·`. Example (code mode):
+ ```
+ → memory_enabled ✓ on 记忆功能总开关
+ auto_coding_memory ✓ on 每轮对话后自动提取记忆(需总开关开启)
+ memory_forbidden_enabled ✗ off 过滤敏感信息
+ ```
+ - Available keys (mode-adaptive):
+ - agent mode: `memory_enabled` (Master memory switch), `memory_proactive` (Proactive memory), `memory_forbidden_enabled` (Forbidden filter);
+ - code mode: `memory_enabled` (Master memory switch), `auto_coding_memory` (Auto coding memory), `memory_forbidden_enabled` (Forbidden filter).
- After toggling, a prompt is shown if a session restart is required for the change to take effect.
+- `open` display contents:
+ - Lists memory directory paths — mode-adaptive:
+ - agent mode: Memory Dir / Project Dir / User Project Dir;
+ - code mode: Coding Memory Dir / Project Dir / User Project Dir.
+ - `Enter` opens the selected directory in the system file manager directly.
+- Tab completion:
+ - `/memory ` — Suggests subcommands (`edit`, `status`, `toggle`, `open`);
+ - `/memory edit ` — Suggests memory file paths (via `getDisplayPath`, relative/tilde-shortened, deduplicated, only existing rule files);
+ - `/memory toggle ` — Suggests toggle keys (mode-adaptive, mirrors the current mode's toggle set);
+ - All completions support prefix filtering.
- Examples:
- - `/memory` — Interactively edit a memory file
- - `/memory list` — List memory files
+ - `/memory` — Open the tabbed console (edit tab)
- `/memory edit memory/MEMORY.md` — Edit a specific memory file
- `/memory status` — View detailed status
- `/memory toggle memory_enabled` — Toggle the master memory switch
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 2fc1d4edf0..9ad1083a9f 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"
@@ -353,26 +353,47 @@
| 命令 | 说明 |
|---|---|
-| `/memory` 或 `/memory edit` | 交互式选择并编辑记忆文件(无参数时列出可选文件) |
-| `/memory list` | 列出所有记忆文件(含大小、行数、修改时间) |
-| `/memory edit <path>` | 打开指定记忆文件进行编辑(通过 `$EDITOR`) |
-| `/memory status` | 显示记忆系统详细状态 |
-| `/memory toggle [key]` | 切换记忆系统开关(无参数时列出可切换项) |
-| `/memory open` | 显示记忆系统各目录路径 |
-
+| `/memory` | 打开页签控制台,默认选中 edit 页签 |
+| `/memory edit` | 打开页签控制台并选中 edit 页签 |
+| `/memory edit <path>` | 直接编辑指定路径的记忆文件(通过 `$EDITOR`) |
+| `/memory status` | 打开页签控制台并选中 status 页签 |
+| `/memory toggle` | 打开页签控制台并选中 toggle 页签 |
+| `/memory toggle <key>` | 直接切换指定记忆系统开关 |
+| `/memory open` | 打开页签控制台并选中 open 页签 |
+
+- 页签控制台:无参数或仅指定子命令(不带操作对象)时打开,包含 edit / status / toggle / open 四个页签。
+ - ←/→ 切换页签;
+ - ↑/↓ 在当前页签列表中移动;
+ - Enter 执行当前选中项;
+ - Ctrl+O 切换全路径显示(edit/open 页签),切换页签时重置为默认(相对路径);
+ - Esc 关闭控制台。
- `status` 展示内容:
- - 当前模式、存储引擎、启用状态、Proactive 状态、Forbidden Filter 状态;
- - 索引状态(FTS5、Vector、Cache)、文件数、分块数;
- - Project Memory、Coding Memory、Auto Memory、External Memory 的统计。
-- `toggle` 可切换项:
- - `memory_enabled` — 记忆总开关;
- - `memory_proactive` — 主动记忆开关;
- - `memory_forbidden_enabled` — Forbidden Filter 开关。
+ - Engine(格式:`builtin (local)`);
+ - 开关行(按模式自适应,`✓ on` / `✗ off`);
+ - 运行时记忆统计(agent 模式显示 "Auto Memory",code 模式显示 "Coding Memory");
+ - Project Memory 统计;
+ - External Memory(如果有)。
+ - 不展示 Current Mode、Index/FTS5/Vector/Cache 等字段。
+- `edit` 页签展示:Project memory(Checked in at)/ Local memory(Saved in)/ User memory(Saved in),Enter 用 `$EDITOR` 打开。
+- `open` 页签展示(按模式自适应):agent 模式为 Memory Dir / Project Dir / User Project Dir;code 模式为 Coding Memory Dir / Project Dir / User Project Dir,Enter 直接打开系统文件管理器。
+- `toggle` 页签展示格式(只显示 key,不显示英文 label,有 `✓ on` / `✗ off` 状态标记和中文描述,无 `·` 分隔符):
+
+ ```
+ → memory_enabled ✓ on 记忆功能总开关
+ auto_coding_memory ✓ on 每轮对话后自动提取记忆(需总开关开启)
+ memory_forbidden_enabled ✗ off 过滤敏感信息
+ ```
+
+ - agent mode:`memory_enabled`(记忆功能总开关)、`memory_proactive`(对话中自动搜索和记录)、`memory_forbidden_enabled`(过滤敏感信息);
+ - code mode:`memory_enabled`(记忆功能总开关)、`auto_coding_memory`(每轮对话后自动提取记忆(需总开关开启))、`memory_forbidden_enabled`(过滤敏感信息)。
- 切换后若需要重启会话生效,会给出提示。
+- Tab 补全:
+ - `/memory edit ` 后显示文件列表(路径用 `getDisplayPath` 展示,去重);
+ - `/memory toggle ` 后显示当前 mode 的 key 列表;
+ - 支持前缀过滤。
- 示例:
- - `/memory` — 交互式编辑记忆文件
- - `/memory list` — 列出记忆文件
- - `/memory edit memory/MEMORY.md` — 编辑指定记忆文件
+ - `/memory` — 打开页签控制台
+ - `/memory edit memory/MEMORY.md` — 直接编辑指定记忆文件
- `/memory status` — 查看详细状态
- `/memory toggle memory_enabled` — 切换记忆总开关
- `/memory open` — 查看记忆目录路径
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 b7e86f60a8..83644d290a 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"
@@ -369,13 +369,24 @@
#### `/memory`(记忆管理)
- 别名:`/mem`。
+- 无参数时打开**页签控制台**(仿 StatusView),含 4 个页签:`edit` / `status` / `toggle` / `open`,默认停在 `edit` 页签。
- 子命令:
- - `list` — 列出所有记忆文件(大小、行数、修改时间)。
- - `edit [path]` — 编辑记忆文件;无参数时交互式选择。
- - `status` — 显示记忆系统详细状态(引擎、索引、Project/Coding/Auto/External Memory 统计)。
- - `toggle [key]` — 切换记忆开关;无参数时列出可切换项(`memory_enabled`、`memory_proactive`、`memory_forbidden_enabled`)。
- - `open` — 显示记忆系统各目录路径。
-- 示例:`/memory status`、`/memory toggle memory_enabled`、`/memory edit memory/MEMORY.md`。
+ - `edit [path]` — 编辑记忆文件;无参数时进入 `edit` 页签(展示 Project memory(Checked in at)/ Local memory(Saved in)/ User memory(Saved in),Enter 用 `$EDITOR` 打开),带路径时直接用 `$EDITOR` 打开(不打开页签控制台)。
+ - `status` — 打开 `status` 页签,展示:Engine(`builtin (local)`)、按模式自适应的开关行(`✓ on` / `✗ off`)、运行时记忆统计(agent 模式 "Auto Memory"、code 模式 "Coding Memory")、Project Memory 统计、External Memory(如果有);不展示 Current Mode、Index/FTS5/Vector/Cache。
+ - `toggle [key]` — 切换记忆开关;无参数时进入 `toggle` 页签列出可切换项,带 key 时直接切换(不打开页签控制台)。
+ - `open` — 打开 `open` 页签,按模式自适应展示目录(agent 模式:Memory Dir / Project Dir / User Project Dir;code 模式:Coding Memory Dir / Project Dir / User Project Dir),Enter 直接打开系统文件管理器。
+- 页签控制台交互:
+ - `←` / `→` — 切换页签(循环)。
+ - `↑` / `↓` — 在列表项间移动光标。
+ - `Enter` — 执行当前页签操作(edit 编辑文件、toggle 切换开关、open 打开目录)。
+ - `Ctrl+O` — 在 `edit` / `open` 页签切换显示完整路径与相对路径,切换页签时重置为默认(相对路径)。
+ - `Esc` — 关闭页签控制台。
+- `toggle` 页签展示格式(只显示 key,不显示英文 label,有 `✓ on` / `✗ off` 状态标记和中文描述,无 `·` 分隔符)。可切换项按当前 mode 过滤:
+ - agent mode:`memory_enabled`(记忆功能总开关)、`memory_proactive`(对话中自动搜索和记录)、`memory_forbidden_enabled`(过滤敏感信息);
+ - code mode:`memory_enabled`(记忆功能总开关)、`auto_coding_memory`(每轮对话后自动提取记忆(需总开关开启))、`memory_forbidden_enabled`(过滤敏感信息)。
+ - 切换后若需重启会话生效会给出提示。
+- Tab 补全:`/memory edit ` 后显示文件列表(路径用 `getDisplayPath` 展示,去重);`/memory toggle ` 后显示当前 mode 的 key 列表;均支持前缀过滤。
+- 示例:`/memory`(打开控制台)、`/memory status`、`/memory toggle memory_enabled`、`/memory edit memory/MEMORY.md`。
#### `/sandbox`(沙箱模式管理)
diff --git "a/docs/zh/\350\207\252\345\212\250\350\256\260\345\277\206.md" "b/docs/zh/\350\207\252\345\212\250\350\256\260\345\277\206.md"
index 2a145872e0..74bbd4f399 100644
--- "a/docs/zh/\350\207\252\345\212\250\350\256\260\345\277\206.md"
+++ "b/docs/zh/\350\207\252\345\212\250\350\256\260\345\277\206.md"
@@ -16,24 +16,32 @@
### 配置文件启用
-在 `config.yaml` 中设置 `auto_memory_enabled`:
+配置键按模式区分:
+
+- **agent 模式**:全局 `auto_memory_enabled`(`config.yaml` 顶层);
+- **code 模式**:`modes.code.memory.auto_coding_memory`(在 `modes.code.memory` 段下)。
```yaml
-# Auto Memory:对话结束后自动提取记忆,按项目隔离存储
+# agent 模式 — 全局开关
auto_memory_enabled: true
+
+# code 模式 — 按模式开关,位于 modes.code.memory 下
+modes:
+ code:
+ memory:
+ auto_coding_memory: true
```
### TUI 命令启用
-在 TUI 终端中使用 `/memory` 命令切换:
+在 TUI 终端中使用 `/memory` 命令打开页签控制台:
```
-/memory # 进入记忆管理界面
-/memory toggle # 显示所有记忆开关
-/memory toggle auto_memory_enabled # 切换自动记忆开关
+/memory # 打开记忆管理页签控制台(默认 edit 页签)
+/memory toggle # 打开页签控制台并选中 toggle 页签
```
-在交互界面中,选择 `Auto-memory: on/off` 选项即可切换。
+页签控制台提供 4 个页签:edit / status / toggle / open,默认选中 edit 页签。使用 ←/→ 切换页签,↑/↓ 在列表中移动,Enter 执行,Ctrl+O 切换全路径(edit/open 页签,切换页签时重置为默认相对路径),Esc 关闭。
---
@@ -92,7 +100,8 @@ flowchart TD
| 配置项 | 说明 | 默认值 |
|--------|------|--------|
-| `auto_memory_enabled` | 是否启用自动记忆提取 | `false` |
+| `auto_memory_enabled` | 自动记忆提取开关(agent 模式,顶层) | `false` |
+| `modes.code.memory.auto_coding_memory` | 自动编码记忆提取开关(code 模式) | `false` |
---
@@ -100,20 +109,32 @@ flowchart TD
### `/memory` 命令
-在 TUI 中输入 `/memory` 命令,会显示记忆管理界面:
+在 TUI 中输入 `/memory` 命令,会打开记忆管理页签控制台(默认选中 edit 页签):
```
Memory
-Select a memory file to edit:
-
- Auto-memory: on [Press Enter to toggle]
- Project memory Checked in at ./JIUWENSWARM.md
- Local memory Saved in ./JIUWENSWARM.local.md
- User memory Saved in ~/.jiuwen/JIUWENSWARM.md
- Open auto-memory folder
+[edit] [status] [toggle] [open]
+ ↑
+ 使用 ←/→ 切换页签,↑/↓ 列表移动,Enter 执行,Ctrl+O 切换全路径(切换页签时重置为默认相对路径),Esc 关闭
+
+--- toggle 页签 ---
+只显示 key(不显示英文 label),有 ✓ on / ✗ off 状态标记和中文描述,无 · 分隔符。
+按模式自适应显示开关:
+
+agent mode:
+ memory_enabled ✓ on 记忆功能总开关
+ memory_proactive ✓ on 对话中自动搜索和记录
+ memory_forbidden_enabled ✗ off 过滤敏感信息
+
+code mode:
+ memory_enabled ✓ on 记忆功能总开关
+ auto_coding_memory ✓ on 每轮对话后自动提取记忆(需总开关开启)
+ memory_forbidden_enabled ✗ off 过滤敏感信息
```
-选择 `Auto-memory: on/off` 行并按 Enter,即可切换自动记忆开关。
+toggle 页签中的开关按当前模式(agent mode / code mode)自适应显示,切换对应开关即可启用/禁用相应记忆功能。
+
+Tab 补全:`/memory edit ` 后显示文件列表(路径用 `getDisplayPath` 展示,去重);`/memory toggle ` 后显示当前 mode 的 key 列表;均支持前缀过滤。
---
diff --git a/jiuwenswarm/agents/harness/common/memory/config.py b/jiuwenswarm/agents/harness/common/memory/config.py
index 11239ddc31..81e267ca93 100644
--- a/jiuwenswarm/agents/harness/common/memory/config.py
+++ b/jiuwenswarm/agents/harness/common/memory/config.py
@@ -264,6 +264,40 @@ def is_proactive_memory(mode: str, config: Optional[Dict[str, Any]] = None) -> b
return False
+def is_auto_memory_enabled(mode: str, config: Optional[Dict[str, Any]] = None) -> bool:
+ """Check if auto-memory (post-conversation extraction) is enabled for the given mode.
+
+ Mode-aware (mirrors is_memory_enabled / is_proactive_memory):
+
+ - code mode: reads ``modes.code.memory.auto_coding_memory`` (default False).
+ This controls the sub-agent fallback extraction specific to code mode.
+ - agent mode: reads the global ``auto_memory_enabled`` flag. Path, default
+ and exception behaviour are preserved verbatim from the legacy
+ ``common.config.is_auto_memory_enabled()`` so agent logic is unchanged.
+
+ Args:
+ config: Optional config dict. If provided, reads from it directly
+ (avoids stale cache). Otherwise reads from config.yaml.
+ """
+ token = (mode or "").strip()
+ if token.startswith("code"):
+ # code mode: 读 modes.code.memory.auto_coding_memory,默认 False
+ try:
+ return bool(_resolve_mode_memory(mode, config).get("auto_coding_memory", False))
+ except Exception as e:
+ logger.warning(f"Invalid auto_coding_memory config, disabled. error: {e}")
+ return False
+ # agent mode: 读全局 auto_memory_enabled,路径/默认/行为全不变
+ try:
+ if config is None:
+ from jiuwenswarm.common.config import get_config
+ config = get_config()
+ return bool(config.get("auto_memory_enabled", False))
+ except Exception:
+ # 与旧实现保持一致:config 读取失败时默认 True
+ return True
+
+
def get_memory_mode(config: Optional[Dict[str, Any]] = None) -> str:
"""读取 ``memory.mode``:``cloud`` 或 ``local``(默认)。"""
memory_cfg = (config or {}).get("memory", {})
diff --git a/jiuwenswarm/agents/harness/common/memory_rpc.py b/jiuwenswarm/agents/harness/common/memory_rpc.py
index fb2f21d260..a2e25af8b2 100644
--- a/jiuwenswarm/agents/harness/common/memory_rpc.py
+++ b/jiuwenswarm/agents/harness/common/memory_rpc.py
@@ -11,7 +11,7 @@ from jiuwenswarm.agents.harness.common.memory import (
get_memory_manager,
is_memory_enabled,
)
-from jiuwenswarm.agents.harness.common.memory.config import is_proactive_memory
+from jiuwenswarm.agents.harness.common.memory.config import is_auto_memory_enabled, is_proactive_memory
from jiuwenswarm.agents.harness.common.memory.external_memory_config import (
get_memory_engine,
is_external_memory_allowed,
@@ -70,6 +70,34 @@ def _is_in_allowed_dirs(abs_path: str, workspace: str, project_dir: str | None =
return False
+def _get_runtime_memory_dirs(workspace: str, project_dir: str | None = None) -> list[str]:
+ """运行时记忆目录(agent 自动写入,对用户只读)。
+
+ 使用父目录以覆盖所有项目子目录:
+ - <workspace>/memory -> agent mode auto memory
+ - <workspace>/coding_memory -> code mode coding memory(含各项目子目录)
+ """
+ return [
+ os.path.normpath(os.path.join(workspace, "memory")),
+ os.path.normpath(os.path.join(workspace, "coding_memory")),
+ ]
+
+
+def _is_runtime_memory_path(abs_path: str, workspace: str, project_dir: str | None = None) -> bool:
+ """abs_path 是否落在运行时记忆目录内(auto/coding memory 文件,禁止手动编辑)。"""
+ if os.name == "nt":
+ abs_lower = abs_path.lower()
+ for d in _get_runtime_memory_dirs(workspace, project_dir):
+ d_lower = d.lower()
+ if abs_lower == d_lower or abs_lower.startswith(d_lower + os.sep):
+ return True
+ return False
+ for d in _get_runtime_memory_dirs(workspace, project_dir):
+ if abs_path == d or abs_path.startswith(d + os.sep):
+ return True
+ return False
+
+
def _validate_edit_path(raw_path: str, workspace: str, project_dir: str | None = None) -> tuple[bool, str]:
normalized = raw_path.replace("\\", "/")
expanded = os.path.expanduser(normalized)
@@ -84,6 +112,10 @@ def _validate_edit_path(raw_path: str, workspace: str, project_dir: str | None =
if _is_in_allowed_dirs(project_resolved, workspace, project_dir):
abs_path = project_resolved
+ # 运行时记忆(auto/coding memory)只读,禁止手动编辑
+ if _is_runtime_memory_path(abs_path, workspace, project_dir):
+ return (False, "runtime memory is read-only, manual editing is not allowed")
+
if _is_in_allowed_dirs(abs_path, workspace, project_dir):
return (True, abs_path)
@@ -102,7 +134,7 @@ def _validate_edit_path(raw_path: str, workspace: str, project_dir: str | None =
if project_dir and parent == os.path.normpath(project_dir):
return (True, abs_path)
- return (False, f"Path not in allowed memory directories: {raw_path}")
+ return (False, "path not in allowed memory directories")
def _classify_memory_file(path: str, workspace: str) -> str:
@@ -256,6 +288,7 @@ async def handle_memory_edit(
"content_preview": "",
"kind": "unknown",
"editable": False,
+ "reason": resolved,
}
exists = Path(resolved).is_file()
@@ -290,8 +323,6 @@ async def handle_memory_status(
mode: str,
params: dict[str, Any],
) -> dict[str, Any]:
- from jiuwenswarm.common.config import is_auto_memory_enabled
-
detailed = params.get("detailed", False)
config = get_config()
@@ -306,7 +337,10 @@ async def handle_memory_status(
"enabled": enabled,
"proactive": proactive,
"forbidden_enabled": _is_forbidden_enabled(config),
- "auto_memory_enabled": is_auto_memory_enabled(),
+ # auto_memory_enabled: agent mode 读全局(保留兼容);code mode 读 auto_coding_memory
+ "auto_memory_enabled": is_auto_memory_enabled(mode, config),
+ # auto_coding_memory: 仅 code mode 有意义;agent mode 返回 None(UI 不展示)
+ "auto_coding_memory": is_auto_memory_enabled(mode, config) if _is_code_mode(mode) else None,
}
if detailed:
@@ -437,12 +471,36 @@ async def handle_memory_toggle(
"needs_restart": True,
}
- if key == "auto_memory_enabled":
- from jiuwenswarm.common.config import (
- is_auto_memory_enabled,
- set_auto_memory_enabled,
+ if key == "auto_coding_memory":
+ # code mode 专属:子 agent 每轮兜底提取开关,写入 modes.code.memory.auto_coding_memory
+ if not _is_code_mode(mode):
+ return {
+ "key": key,
+ "old_value": False,
+ "new_value": False,
+ "mode_affected": "",
+ "needs_restart": False,
+ "error": f"auto_coding_memory is only valid in code mode (current: {mode})",
+ }
+ old = is_auto_memory_enabled(mode, config)
+ new = not old
+ _update_mode_memory_config(mode, "auto_coding_memory", new)
+ logger.info(
+ "[memory_rpc] Toggle auto_coding_memory: old=%s -> new=%s (mode=%s)",
+ old, new, mode,
)
- old = is_auto_memory_enabled()
+ return {
+ "key": key,
+ "old_value": old,
+ "new_value": new,
+ "mode_affected": mode,
+ "needs_restart": True,
+ }
+
+ if key == "auto_memory_enabled":
+ # legacy 全局开关(agent mode 对话后提取);UI 不暴露,保留兼容
+ from jiuwenswarm.common.config import set_auto_memory_enabled
+ old = bool(config.get("auto_memory_enabled", False))
new = not old
set_auto_memory_enabled(new)
logger.info(
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory-path-utils.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory-path-utils.ts
new file mode 100644
index 0000000000..0f80bebdd9
--- /dev/null
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory-path-utils.ts
@@ -0,0 +1,152 @@
+import { statSync } from "node:fs";
+import { homedir } from "node:os";
+import { dirname, join, parse, relative } from "node:path";
+
+// ---------------------------------------------------------------------------
+// Path display utilities (aligned with Claude Code's getDisplayPath)
+// ---------------------------------------------------------------------------
+//
+// 统一的路径展示工具:从 memory.ts 的 getDisplayPath 与 app-screen.ts 的
+// mvDisplayPath 合并而来。二者原本各有侧重——
+// getDisplayPath: 用 path.relative() 精确计算,处理 Windows 跨盘/Unicode/
+// 大小写问题,且能产生 ../ 前缀路径(来自 gitRoot 候选)。
+// mvDisplayPath: 纯前缀匹配,简单但无法产生 ../ 路径;空结果用 "." 表示
+// 当前目录(Unix 惯例)。
+// 合并后取两者之长:保留 relative() 的稳健性 + 空路径→"." 的友好展示,
+// 并接受可选 gitRoot 参数避免调用方重复计算。
+
+/**
+ * Convert an absolute path to the shortest display-friendly path.
+ * Mirrors Claude Code's getDisplayPath logic — generates ALL candidate paths
+ * and picks the shortest one:
+ *
+ * Candidates:
+ * 1. Relative from git root (e.g. ".jiuwen/rules/foo.md", "../JIUWENSWARM.md")
+ * 2. Relative from projectDir (e.g. "JIUWENSWARM.local.md", ".jiuwen/rules/foo.md")
+ * 3. Tilde notation (e.g. "~/.jiuwen/JIUWENSWARM.md")
+ *
+ * Winner = shortest candidate.
+ * Empty candidate (file === base dir) is shown as "." (current directory).
+ *
+ * All output uses forward slashes. ../ prefix paths are allowed (from gitRoot
+ * candidate only; projectDir candidate skips them as unfriendly).
+ *
+ * On Windows, THREE critical issues must be handled:
+ * - path.relative() returns absolute paths for cross-drive paths — must discard.
+ * - Case mismatch: getCurrentProjectDir() lowercases on Windows, backend doesn't.
+ * - Unicode bug: Node.js path.relative() silently drops \ from multi-byte paths.
+ *
+ * @param filePath Absolute path to the file/dir to display.
+ * @param projectDir Current project directory (CWD).
+ * @param gitRoot Optional pre-computed git root. If omitted, discovered from
+ * projectDir via findGitRoot(). Pass it in when the caller
+ * already has it to avoid redundant filesystem walks.
+ */
+export function getDisplayPath(
+ filePath: string,
+ projectDir: string,
+ gitRoot?: string | null,
+): string {
+ const fileSlashes = filePath.replace(/\\/g, "/");
+ const fileNorm = process.platform === "win32" ? fileSlashes.toLowerCase() : fileSlashes;
+ const homeDir = homedir();
+ const homeDirSlashes = homeDir.replace(/\\/g, "/");
+ const homeDirNorm = process.platform === "win32" ? homeDirSlashes.toLowerCase() : homeDirSlashes;
+
+ // Collect all valid candidate paths, then pick the shortest
+ const candidates: string[] = [];
+
+ // Resolve gitRoot: use provided value or discover from projectDir
+ const resolvedGitRoot = gitRoot !== undefined ? gitRoot : findGitRoot(projectDir);
+
+ // Candidate 1: relative from git root (only if file is inside projectDir)
+ // 守卫:仅当文件位于 projectDir 内部时才采用 git-root 相对路径候选。
+ // 否则(文件在 projectDir 的父级/祖先目录)git-root 相对路径会丢掉 ../
+ // 前缀,把父目录文件伪装成当前目录文件,误导用户。此时应只保留 candidate 2
+ // 的 projectDir 相对路径(必带 ../ 前缀)。
+ const fileInsideProject = isAncestorOrSelfDir(projectDir, filePath);
+ if (resolvedGitRoot && fileInsideProject) {
+ const gitRootSlashes = resolvedGitRoot.replace(/\\/g, "/");
+ const gitRootNorm = process.platform === "win32" ? gitRootSlashes.toLowerCase() : gitRootSlashes;
+ const projectDirSlashes = projectDir.replace(/\\/g, "/");
+ const projectDirNorm = process.platform === "win32" ? projectDirSlashes.toLowerCase() : projectDirSlashes;
+ // Only use git root as base if projectDir is inside the git repo
+ if (projectDirNorm.startsWith(gitRootNorm + "/") || projectDirNorm === gitRootNorm) {
+ const relFromGit = relative(gitRootNorm, fileNorm);
+ // Discard cross-drive absolute paths from relative(); allow empty (file === gitRoot)
+ if (!relFromGit.startsWith("/") && !/^[A-Za-z]:/.test(relFromGit)) {
+ const display = relative(gitRootSlashes, fileSlashes).replace(/\\/g, "/");
+ candidates.push(display);
+ }
+ }
+ }
+
+ // Candidate 2: relative from projectDir (skip cross-drive & "../" paths)
+ // 允许空字符串(file === projectDir → 显示 ".");跳过 ../ 前缀(不友好)。
+ const projectDirSlashes = projectDir.replace(/\\/g, "/");
+ const projectDirNorm = process.platform === "win32" ? projectDirSlashes.toLowerCase() : projectDirSlashes;
+ const relFromProj = relative(projectDirNorm, fileNorm);
+ if (!relFromProj.startsWith("/") && !/^[A-Za-z]:/.test(relFromProj) && !relFromProj.startsWith("..")) {
+ const display = relative(projectDirSlashes, fileSlashes).replace(/\\/g, "/");
+ candidates.push(display);
+ }
+
+ // Candidate 3: tilde notation (if file is in home directory)
+ if (fileNorm.startsWith(homeDirNorm + "/") || fileNorm === homeDirNorm) {
+ const tildePath = "~" + fileSlashes.slice(homeDirSlashes.length);
+ candidates.push(tildePath);
+ }
+
+ // Pick the shortest candidate; empty string means "current dir" → "."
+ if (candidates.length > 0) {
+ return candidates
+ .map((c) => (c.length === 0 ? "." : c))
+ .reduce((shortest, c) => (c.length < shortest.length ? c : shortest));
+ }
+
+ // Fallback: file name only (avoid overly long absolute paths)
+ const baseName = fileSlashes.split("/").pop() ?? fileSlashes;
+ return baseName || fileSlashes;
+}
+
+/**
+ * Find the git repository root directory.
+ * Walks upward from cwd looking for a .git directory or file (worktree/submodule).
+ * Returns the git root path if found, or null if not in a git repo.
+ * Mirrors Claude Code's findGitRoot logic.
+ */
+export function findGitRoot(cwd: string): string | null {
+ let current = cwd;
+ const root = parse(current).root;
+ while (current !== root) {
+ try {
+ const gitPath = join(current, ".git");
+ const stat = statSync(gitPath);
+ // .git can be a directory (regular repo) or file (worktree/submodule)
+ if (stat.isDirectory() || stat.isFile()) {
+ return current;
+ }
+ } catch {
+ // .git doesn't exist at this level, continue walking up
+ }
+ current = dirname(current);
+ }
+ return null;
+}
+
+/**
+ * 判断 ancestor 是否是 target 的祖先目录或本身(Windows 大小写不敏感)。
+ *
+ * 用于识别"文件位于 projectDir 的上级目录"这一场景——后端
+ * `_validate_edit_path` 只白名单 project_dir 单层,会拒绝编辑 projectDir
+ * 祖先目录里的 JIUWENSWARM.md / JIUWENSWARM.local.md;同时 getDisplayPath
+ * 在父目录是 git root 时会把这类文件显示成无 ../ 的当前目录文件(伪装)。
+ * 两处都需要用此函数识别并特殊处理。
+ */
+export function isAncestorOrSelfDir(ancestor: string, target: string): boolean {
+ const a = ancestor.replace(/\\/g, "/").replace(/\/$/, "");
+ const t = target.replace(/\\/g, "/").replace(/\/$/, "");
+ const aNorm = process.platform === "win32" ? a.toLowerCase() : a;
+ const tNorm = process.platform === "win32" ? t.toLowerCase() : t;
+ return aNorm === tNorm || tNorm.startsWith(aNorm + "/");
+}
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.ts
index 744b606043..1e2a04bdb3 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.ts
@@ -4,8 +4,9 @@ import { dirname, join, parse, relative } from "node:path";
import { addError, addInfo, makeItem } from "../helpers.js";
import { CommandKind, type SlashCommand } from "../types.js";
import { getEditorInfo } from "../../utils/editor.js";
+import { getDisplayPath, findGitRoot, isAncestorOrSelfDir } from "./memory-path-utils.js";
-interface MemoryFile {
+export interface MemoryFile {
path: string;
relative_path: string;
kind: string;
@@ -21,6 +22,7 @@ interface MemoryEditResult {
content_preview: string;
kind: string;
editable: boolean;
+ reason?: string;
}
interface MemoryStatusResult {
@@ -31,6 +33,8 @@ interface MemoryStatusResult {
proactive: boolean;
forbidden_enabled: boolean;
auto_memory_enabled: boolean;
+ /** code mode 专属:子 agent 兜底提取开关;agent mode 为 null(UI 不展示) */
+ auto_coding_memory?: boolean | null;
index?: {
available: boolean;
provider?: string | null;
@@ -80,162 +84,6 @@ interface MemoryOpenResult {
auto_memory_dir?: string;
}
-// ---------------------------------------------------------------------------
-// Path display utilities (aligned with Claude Code's getDisplayPath)
-// ---------------------------------------------------------------------------
-
-/**
- * Convert an absolute path to a display-friendly relative path.
- * Mirrors Claude Code's getDisplayPath logic — uses git root as base for
- * computing relative paths (not the deep projectDir subdirectory), which
- * produces short paths like ".jiuwen/rules/foo.md" instead of long
- * "../../../../../.jiuwen/rules/foo.md".
- *
- * Priority order (aligned with Claude Code):
- * 1. If git root found → compute relative path from git root
- * (e.g. ".jiuwen/rules/foo.md", "JIUWENSWARM.md")
- * 2. If no git root → compute relative path from projectDir
- * (e.g. "../JIUWENSWARM.md", ".jiuwen/rules/foo.md")
- * 3. If file is in home directory → use tilde notation
- * (e.g. "~/.jiuwen/JIUWENSWARM.md")
- * 4. Otherwise → fallback to absolute path with forward slashes
- *
- * On Windows, THREE critical issues must be handled:
- * - path.relative() returns absolute paths when source/target are on different
- * drives (e.g. E: vs C:) — must NOT treat these as valid relative paths.
- * - Case mismatch: getCurrentProjectDir() lowercases paths on Windows, but
- * backend returns original-case paths. We normalize both paths to the same
- * case before computing relative().
- * - **Unicode path bug**: Node.js path.relative() on Windows silently drops
- * backslash separators from paths containing multi-byte characters (e.g.
- * C:\Users\李雯琳 → "C:Users李雯琳"), producing garbage output. We convert
- * all backslashes to forward slashes before calling relative(), which avoids
- * this bug because forward slashes are also valid separators on Windows.
- *
- * All output is normalized to forward slashes (aligned with Claude Code).
- */
-/**
- * Convert an absolute path to the shortest display-friendly path.
- * Mirrors Claude Code's getDisplayPath logic — generates ALL candidate paths
- * and picks the shortest one:
- *
- * Candidates:
- * 1. Relative from git root (e.g. ".jiuwen/rules/foo.md", "../JIUWENSWARM.md")
- * 2. Relative from projectDir (e.g. "../../JIUWENSWARM.md", ".jiuwen/rules/foo.md")
- * 3. Tilde notation (e.g. "~/.jiuwen/JIUWENSWARM.md")
- *
- * Winner = shortest candidate.
- * Examples:
- * - ../JIUWENSWARM.md (17 chars) beats ~/AppData/Local/.../JIUWENSWARM.md (49 chars)
- * - .jiuwen/rules/git.md (21 chars) beats ../../.jiuwen/rules/git.md (26 chars)
- * - ~/.jiuwen/JIUWENSWARM.md (22 chars) beats ../JIUWENSWARM.md when in deep subdir
- *
- * All output uses forward slashes. Claude Code allows ../ prefix paths.
- *
- * On Windows, THREE critical issues must be handled:
- * - path.relative() returns absolute paths for cross-drive paths — must discard.
- * - Case mismatch: getCurrentProjectDir() lowercases on Windows, backend doesn't.
- * - Unicode bug: Node.js path.relative() silently drops \ from multi-byte paths.
- */
-function getDisplayPath(filePath: string, projectDir: string): string {
- const fileSlashes = filePath.replace(/\\/g, "/");
- const fileNorm = process.platform === "win32" ? fileSlashes.toLowerCase() : fileSlashes;
- const homeDir = homedir();
- const homeDirSlashes = homeDir.replace(/\\/g, "/");
- const homeDirNorm = process.platform === "win32" ? homeDirSlashes.toLowerCase() : homeDirSlashes;
-
- // Collect all valid candidate paths, then pick the shortest
- const candidates: string[] = [];
-
- // Candidate 1: relative from git root (if inside git repo)
- // 守卫:仅当文件位于 projectDir 内部时才采用 git-root 相对路径候选。
- // 否则(文件在 projectDir 的父级/祖先目录)git-root 相对路径会丢掉 ../
- // 前缀,把父目录文件伪装成当前目录文件,误导用户。此时应只保留 candidate 2
- // 的 projectDir 相对路径(必带 ../ 前缀)。
- const fileInsideProject = isAncestorOrSelfDir(projectDir, filePath);
- const gitRoot = findGitRoot(projectDir);
- if (gitRoot && fileInsideProject) {
- const gitRootSlashes = gitRoot.replace(/\\/g, "/");
- const gitRootNorm = process.platform === "win32" ? gitRootSlashes.toLowerCase() : gitRootSlashes;
- const projectDirSlashes = projectDir.replace(/\\/g, "/");
- const projectDirNorm = process.platform === "win32" ? projectDirSlashes.toLowerCase() : projectDirSlashes;
- // Only use git root as base if projectDir is inside the git repo
- if (projectDirNorm.startsWith(gitRootNorm + "/") || projectDirNorm === gitRootNorm) {
- const relFromGit = relative(gitRootNorm, fileNorm);
- // Discard cross-drive absolute paths from relative()
- if (relFromGit && !relFromGit.startsWith("/") && !/^[A-Za-z]:/.test(relFromGit)) {
- const display = relative(gitRootSlashes, fileSlashes).replace(/\\/g, "/");
- candidates.push(display);
- }
- }
- }
-
- // Candidate 2: relative from projectDir
- const projectDirSlashes = projectDir.replace(/\\/g, "/");
- const projectDirNorm = process.platform === "win32" ? projectDirSlashes.toLowerCase() : projectDirSlashes;
- const relFromProj = relative(projectDirNorm, fileNorm);
- if (relFromProj && !relFromProj.startsWith("/") && !/^[A-Za-z]:/.test(relFromProj)) {
- const display = relative(projectDirSlashes, fileSlashes).replace(/\\/g, "/");
- candidates.push(display);
- }
-
- // Candidate 3: tilde notation (if file is in home directory)
- if (fileNorm.startsWith(homeDirNorm + "/") || fileNorm === homeDirNorm) {
- const tildePath = "~" + fileSlashes.slice(homeDirSlashes.length);
- candidates.push(tildePath);
- }
-
- // Pick the shortest candidate — this is exactly what Claude Code does
- if (candidates.length > 0) {
- return candidates.reduce((shortest, c) => c.length < shortest.length ? c : shortest, candidates[0]);
- }
-
- // Fallback: absolute path with forward slashes
- return fileSlashes;
-}
-
-/**
- * Find the git repository root directory.
- * Walks upward from cwd looking for a .git directory or file (worktree/submodule).
- * Returns the git root path if found, or null if not in a git repo.
- * Mirrors Claude Code's findGitRoot logic.
- */
-function findGitRoot(cwd: string): string | null {
- let current = cwd;
- const root = parse(current).root;
- while (current !== root) {
- try {
- const gitPath = join(current, ".git");
- const stat = statSync(gitPath);
- // .git can be a directory (regular repo) or file (worktree/submodule)
- if (stat.isDirectory() || stat.isFile()) {
- return current;
- }
- } catch {
- // .git doesn't exist at this level, continue walking up
- }
- current = dirname(current);
- }
- return null;
-}
-
-/**
- * 判断 ancestor 是否是 target 的祖先目录或本身(Windows 大小写不敏感)。
- *
- * 用于识别"文件位于 projectDir 的上级目录"这一场景——后端
- * `_validate_edit_path` 只白名单 project_dir 单层,会拒绝编辑 projectDir
- * 祖先目录里的 JIUWENSWARM.md / JIUWENSWARM.local.md;同时 getDisplayPath
- * 在父目录是 git root 时会把这类文件显示成无 ../ 的当前目录文件(伪装)。
- * 两处都需要用此函数识别并特殊处理。
- */
-function isAncestorOrSelfDir(ancestor: string, target: string): boolean {
- const a = ancestor.replace(/\\/g, "/").replace(/\/$/, "");
- const t = target.replace(/\\/g, "/").replace(/\/$/, "");
- const aNorm = process.platform === "win32" ? a.toLowerCase() : a;
- const tNorm = process.platform === "win32" ? t.toLowerCase() : t;
- return aNorm === tNorm || tNorm.startsWith(aNorm + "/");
-}
-
// ---------------------------------------------------------------------------
// Frontend-side memory file discovery (mirrors Claude Code's unguarded walk)
// ---------------------------------------------------------------------------
@@ -255,7 +103,7 @@ function probeFile(absPath: string, relPath: string, kind: string): MemoryFile {
try {
const stat = statSync(absPath);
const content = readFileSync(absPath, "utf-8");
- const lines = content.split("\n").length;
+ const lines = content.replace(/[\r\n]+$/, "").split(/\r\n|\n/).length;
return {
path: absPath,
relative_path: relPath,
@@ -370,356 +218,150 @@ function discoverMemoryFilesFromFs(cwd: string): MemoryFile[] {
return results;
}
-function formatSize(bytes: number): string {
- if (bytes < 1024) return `${bytes} B`;
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
-}
-
-function formatTime(mtime: number): string {
- if (!mtime) return "";
- const diff = Date.now() / 1000 - mtime;
- if (diff < 60) return "just now";
- if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
- if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
- return `${Math.floor(diff / 86400)}d ago`;
-}
-
function modeToShort(mode: string): string {
if (mode.startsWith("code")) return "code";
return mode.replace("agent.", "");
}
-async function showMemoryOverview(ctx: import("../types.js").CommandContext): Promise<void> {
- const mode = modeToShort(ctx.mode);
- try {
- const payload = await ctx.request<MemoryStatusResult>("memory.status", {
- detailed: true,
- mode,
- });
-
- const items: { label: string; value: string; description?: string }[] = [];
-
- items.push({ label: "Mode", value: payload.current_mode });
- items.push({ label: "Engine", value: `${payload.engine} (${payload.storage_mode})` });
- items.push({ label: "Enabled", value: payload.enabled ? "✓ on" : "✗ off" });
- items.push({ label: "Proactive", value: payload.proactive ? "✓ on" : "✗ off" });
- items.push({ label: "Forbidden Filter", value: payload.forbidden_enabled ? "✓ on" : "✗ off" });
- items.push({ label: "Auto Memory", value: payload.auto_memory_enabled ? "✓ on" : "✗ off" });
-
- if (payload.index) {
- items.push({
- label: "Index",
- value: `Files: ${payload.index.files_count} Chunks: ${payload.index.chunks_count}`,
- description: `FTS: ${payload.index.fts?.available ? "✓" : "✗"} Vector: ${payload.index.vector?.available ? "✓" : "✗"}`,
- });
- }
-
- if (payload.project_memory) {
- items.push({
- label: "Project Memory",
- value: `${payload.project_memory.files_count} files`,
- description: `${payload.project_memory.total_chars} / ${payload.project_memory.max_chars} chars`,
- });
- if (payload.project_memory.project_dir) {
- items.push({
- label: "Project Dir",
- value: payload.project_memory.project_dir,
- });
+/** 收集并排序可编辑规则文件(合并后端 list + 前端发现,含占位条目)。
+ * 供 list / edit 页签复用。 */
+export async function collectOrderedMemoryFiles(
+ ctx: import("../types.js").CommandContext,
+ mode: string,
+): Promise<{ files: MemoryFile[]; userMemoryPath: string; gitRoot: string | null; projectDir: string }> {
+ const projectDir = ctx.getCurrentProjectDir();
+ const listPayload = await ctx.request<{ files: MemoryFile[] }>("memory.list", { mode });
+ const files = listPayload.files ?? [];
+
+ // Frontend-side unguarded traversal to fill gaps
+ const discovered = discoverMemoryFilesFromFs(projectDir);
+ const frontendByPath = new Map<string, MemoryFile>();
+ for (const f of discovered) {
+ frontendByPath.set(normalizePathKey(f.path), f);
+ }
+ const seenPaths = new Set(files.map((f) => normalizePathKey(f.path)));
+ const mergedFiles: MemoryFile[] = files.map((f) => {
+ if (f.relative_path === f.path) {
+ const frontend = frontendByPath.get(normalizePathKey(f.path));
+ if (frontend && frontend.relative_path !== frontend.path) {
+ return { ...f, relative_path: frontend.relative_path };
}
}
-
- if (payload.coding_memory) {
- items.push({
- label: "Coding Memory",
- value: `${payload.coding_memory.files_count} files`,
- description: `${payload.coding_memory.total_chars} chars`,
- });
- }
-
- if (payload.auto_memory) {
- items.push({
- label: "Auto Memory",
- value: `${payload.auto_memory.files_count} files`,
- description: `${payload.auto_memory.total_chars} chars`,
- });
- }
-
- if (payload.external_memory) {
- items.push({
- label: "External Memory",
- value: `${payload.external_memory.provider} ${payload.external_memory.enabled ? "✓" : "✗"}`,
- });
+ return f;
+ });
+ for (const f of discovered) {
+ if (!seenPaths.has(normalizePathKey(f.path))) {
+ mergedFiles.push(f);
+ seenPaths.add(normalizePathKey(f.path));
}
+ }
- ctx.addItem(
- makeItem(ctx.sessionId, "info", "Memory Status", "m", {
- view: "kv",
- title: "Memory",
- items,
- }),
- );
-
- ctx.addItem(
- addInfo(
- ctx.sessionId,
- "Usage: /memory list|edit|status|toggle|open",
- "i",
- ),
- );
- } catch (err) {
- ctx.addItem(
- addError(ctx.sessionId, `Failed to get memory status: ${err instanceof Error ? err.message : String(err)}`),
+ const homeDir = homedir();
+ const gitRoot = findGitRoot(projectDir);
+ const userMemoryPath = join(homeDir, ".jiuwen", "JIUWENSWARM.md");
+ const filePathLowerFn = (p: string) => (process.platform === "win32" ? p.toLowerCase() : p);
+
+ const projectMemoryFile = mergedFiles.find(
+ (f) => f.kind === "project"
+ && f.path.endsWith("JIUWENSWARM.md")
+ && !f.path.endsWith("JIUWENSWARM.local.md"),
+ );
+ const localMemoryFile = mergedFiles.find(
+ (f) => f.kind === "local" && f.path.endsWith("JIUWENSWARM.local.md"),
+ );
+ const userMemoryFile = mergedFiles.find(
+ (f) => filePathLowerFn(f.path) === filePathLowerFn(userMemoryPath),
+ );
+ const projectRules = mergedFiles.filter(
+ (f) => f.kind === "project" && f !== projectMemoryFile && f !== localMemoryFile,
+ );
+ const userRules = mergedFiles.filter(
+ (f) => f.kind === "user" && filePathLowerFn(f.path) !== filePathLowerFn(userMemoryPath),
+ );
+
+ const orderedFiles: MemoryFile[] = [];
+ if (projectMemoryFile) orderedFiles.push(projectMemoryFile);
+ for (const f of projectRules) orderedFiles.push(f);
+ if (localMemoryFile) orderedFiles.push(localMemoryFile);
+ if (userMemoryFile) orderedFiles.push(userMemoryFile);
+ for (const f of userRules) orderedFiles.push(f);
+
+ const projMemBase = gitRoot || projectDir;
+ if (!projectMemoryFile) {
+ orderedFiles.unshift(probeFile(join(projMemBase, "JIUWENSWARM.md"), "JIUWENSWARM.md", "project"));
+ }
+ if (!localMemoryFile) {
+ const insertIdx = orderedFiles.findIndex(
+ (f) => filePathLowerFn(f.path) === filePathLowerFn(userMemoryPath),
);
+ const localProbe = probeFile(join(projMemBase, "JIUWENSWARM.local.md"), "JIUWENSWARM.local.md", "local");
+ if (insertIdx >= 0) {
+ orderedFiles.splice(insertIdx, 0, localProbe);
+ } else {
+ orderedFiles.push(localProbe);
+ }
}
+ if (!userMemoryFile) {
+ orderedFiles.push(probeFile(userMemoryPath, "JIUWENSWARM.md", "user"));
+ }
+ return { files: orderedFiles, userMemoryPath, gitRoot, projectDir };
}
-async function listMemory(ctx: import("../types.js").CommandContext): Promise<void> {
- // Aligned with Claude Code: /memory list uses an interactive selector
- // with two-column layout (label + description), same as the default /memory action.
- await showMemorySelector(ctx);
-}
-
-/**
- * Show memory file selector — the core UI shared by /memory and /memory list.
- * EXACTLY aligned with Claude Code's /memory display format:
- *
- * 1. Project memory Checked in at ./CLAUDE.md
- * 2. .claude/rules/git.md
- * 3. .claude/rules/testing.md
- * 4. User memory Saved in ~/.claude/CLAUDE.md
- *
- * Key principles (mirroring Claude Code exactly):
- * - "Project memory" and "User memory" are short labels with descriptions
- * showing "Checked in at"/"Saved in" + the relative path
- * - Rules files (.jiuwen/rules/*.md) are listed with their relative path
- * as the ONLY label — NO description column (same as Claude Code)
- * - Paths are always relative (from git root when available), using /
- * separators, never absolute or long ../../ paths
- * - Sort order: Project memory → project rules → Local memory → User memory → user rules
- * (mirrors Claude Code's project-first ordering)
- *
- * Uses ctx.askQuestions → SelectList for proper two-column rendering that
- * never truncates the label.
- */
-// Sentinel values for non-file actions in the selector
-const ACTION_TOGGLE_MEMORY_ENABLED = "__toggle_memory_enabled__";
-const ACTION_TOGGLE_AUTO_MEMORY = "__toggle_auto_memory__";
-const ACTION_OPEN_AUTO_MEMORY_FOLDER = "__open_auto_memory_folder__";
-
-async function showMemorySelector(ctx: import("../types.js").CommandContext): Promise<void> {
+/** edit 页签:纯文件选择器(无开关/打开文件夹行),选中即用 $EDITOR 打开。 */
+async function editMemorySelector(ctx: import("../types.js").CommandContext): Promise<void> {
const mode = modeToShort(ctx.mode);
- const projectDir = ctx.getCurrentProjectDir();
-
try {
- // Fetch both memory file list and status (for auto-memory toggle state)
- const [listPayload, statusPayload] = await Promise.all([
- ctx.request<{ files: MemoryFile[] }>("memory.list", { mode }),
- ctx.request<MemoryStatusResult>("memory.status", { detailed: true, mode }),
- ]);
- const files = listPayload.files ?? [];
- const memoryEnabled = statusPayload.enabled ?? false;
- const autoMemoryEnabled = statusPayload.auto_memory_enabled ?? false;
-
- // Frontend-side unguarded traversal to fill gaps
- const discovered = discoverMemoryFilesFromFs(projectDir);
- const frontendByPath = new Map<string, MemoryFile>();
- for (const f of discovered) {
- frontendByPath.set(normalizePathKey(f.path), f);
- }
- const seenPaths = new Set(files.map((f) => normalizePathKey(f.path)));
- const mergedFiles: MemoryFile[] = files.map((f) => {
- if (f.relative_path === f.path) {
- const frontend = frontendByPath.get(normalizePathKey(f.path));
- if (frontend && frontend.relative_path !== frontend.path) {
- return { ...f, relative_path: frontend.relative_path };
- }
- }
- return f;
- });
- for (const f of discovered) {
- if (!seenPaths.has(normalizePathKey(f.path))) {
- mergedFiles.push(f);
- seenPaths.add(normalizePathKey(f.path));
- }
- }
-
- const homeDir = homedir();
- const gitRoot = findGitRoot(projectDir);
- const homeDirLower = process.platform === "win32" ? homeDir.toLowerCase() : homeDir;
- const userMemoryPath = join(homeDir, ".jiuwen", "JIUWENSWARM.md");
- const filePathLowerFn = (p: string) => process.platform === "win32" ? p.toLowerCase() : p;
-
- // Categorize files into groups, aligned with Claude Code's display order.
- const projectMemoryFile = mergedFiles.find(
- (f) => f.kind === "project"
- && f.path.endsWith("JIUWENSWARM.md")
- && !f.path.endsWith("JIUWENSWARM.local.md")
- && !f.path.endsWith(".jiuwen/JIUWENSWARM.md"),
- );
- const localMemoryFile = mergedFiles.find(
- (f) => f.kind === "local" && f.path.endsWith("JIUWENSWARM.local.md"),
- );
- const userMemoryFile = mergedFiles.find(
- (f) => filePathLowerFn(f.path) === filePathLowerFn(userMemoryPath),
- );
-
- // Project-level rules files: any project-kind file that is NOT the main JIUWENSWARM.md
- const projectRules = mergedFiles.filter(
- (f) => f.kind === "project"
- && f !== projectMemoryFile
- && f !== localMemoryFile,
- );
-
- // User-level rules files: any user-kind file that is NOT the main user JIUWENSWARM.md
- const userRules = mergedFiles.filter(
- (f) => f.kind === "user"
- && filePathLowerFn(f.path) !== filePathLowerFn(userMemoryPath),
- );
-
- // Build ordered file list matching Claude Code's exact order:
- // Project memory → project rules → Local memory → User memory → user rules
- const orderedFiles: MemoryFile[] = [];
- if (projectMemoryFile) orderedFiles.push(projectMemoryFile);
- for (const f of projectRules) orderedFiles.push(f);
- if (localMemoryFile) orderedFiles.push(localMemoryFile);
- if (userMemoryFile) orderedFiles.push(userMemoryFile);
- for (const f of userRules) orderedFiles.push(f);
-
- // Always provide JIUWENSWARM.md / JIUWENSWARM.local.md entries so users can create them
- const projMemBase = gitRoot || projectDir;
- if (!projectMemoryFile) {
- orderedFiles.unshift(probeFile(join(projMemBase, "JIUWENSWARM.md"), "JIUWENSWARM.md", "project"));
- }
- if (!localMemoryFile) {
- const insertIdx = orderedFiles.findIndex(
- (f) => filePathLowerFn(f.path) === filePathLowerFn(userMemoryPath),
- );
- const localProbe = probeFile(join(projMemBase, "JIUWENSWARM.local.md"), "JIUWENSWARM.local.md", "local");
- if (insertIdx >= 0) {
- orderedFiles.splice(insertIdx, 0, localProbe);
- } else {
- orderedFiles.push(localProbe);
- }
- }
- if (!userMemoryFile) {
- orderedFiles.push(probeFile(userMemoryPath, "JIUWENSWARM.md", "user"));
- }
-
- // Build options — EXACTLY aligned with Claude Code's /memory display
- // Aligned with Claude Code format:
- // 1. Memory: on/off (toggle — control CodingMemoryRail/ProjectMemoryRail)
- // 2. Auto-memory: on/off (toggle — control auto memory extraction)
- // 3. Project memory Checked in at ./CLAUDE.md
- // 4. .claude/rules/git.md
- // 5. User memory Saved in ~/.claude/CLAUDE.md
- // 6. Open auto-memory folder (only when auto-memory is on)
-
- const options: { label: string; description: string | undefined; value: string }[] = [];
-
- // 1. Memory enabled toggle — control CodingMemoryRail and ProjectMemoryRail loading
- options.push({
- label: `Memory: ${memoryEnabled ? "on" : "off"}`,
- description: memoryEnabled ? "Press Enter to toggle" : "Memory disabled - files won't be auto-loaded",
- value: ACTION_TOGGLE_MEMORY_ENABLED,
- });
-
- // 2. Auto-memory toggle — control auto memory extraction after conversation ends
- options.push({
- label: `Auto-memory: ${autoMemoryEnabled ? "on" : "off"}`,
- description: "Press Enter to toggle",
- value: ACTION_TOGGLE_AUTO_MEMORY,
- });
-
- // 3. Memory file entries
- for (const f of orderedFiles) {
- const filePathLower = filePathLowerFn(f.path);
+ const { files, userMemoryPath, gitRoot, projectDir } = await collectOrderedMemoryFiles(ctx, mode);
+ const filePathLowerFn = (p: string) => (process.platform === "win32" ? p.toLowerCase() : p);
+ const options = files.map((f) => {
const displayPath = getDisplayPath(f.path, projectDir);
-
let label: string;
let description: string | undefined;
-
- if (filePathLower === filePathLowerFn(userMemoryPath)) {
+ if (filePathLowerFn(f.path) === filePathLowerFn(userMemoryPath)) {
label = "User memory";
description = `Saved in ${displayPath}`;
- } else if (f.kind === "project" && f.path.endsWith("JIUWENSWARM.md") && !f.path.endsWith("JIUWENSWARM.local.md") && !f.path.endsWith(".jiuwen/JIUWENSWARM.md")) {
+ } else if (
+ f.kind === "project"
+ && f.path.endsWith("JIUWENSWARM.md")
+ && !f.path.endsWith("JIUWENSWARM.local.md")
+ && !f.path.endsWith(".jiuwen/JIUWENSWARM.md")
+ ) {
label = "Project memory";
description = `${gitRoot ? "Checked in at" : "Saved in"} ${displayPath}`;
} else if (f.kind === "local" && f.path.endsWith("JIUWENSWARM.local.md")) {
label = "Local memory";
description = `Saved in ${displayPath}`;
} else {
- // Rules files — just show the relative path as label, NO description
label = displayPath;
description = undefined;
}
-
- options.push({ label, description, value: f.path });
- }
-
- // 3. Open auto-memory folder — only on Windows + when auto-memory is enabled
- // Linux/macOS: not shown because xdg-open/file-manager support varies and cannot be tested
- if (autoMemoryEnabled && process.platform === "win32") {
- options.push({
- label: "Open auto-memory folder",
- description: undefined,
- value: ACTION_OPEN_AUTO_MEMORY_FOLDER,
- });
- }
+ return { label, description, value: f.path };
+ });
let selectedValue: string | undefined;
try {
const [answer] = await ctx.askQuestions(
[
{
- header: "Memory",
- question: "Select an action:",
- options: options.map((opt) => ({
- label: opt.label,
- description: opt.description,
- })),
+ header: "Memory edit",
+ question: "Select a file to edit:",
+ options: options.map((o) => ({ label: o.label, description: o.description })),
},
],
"local_command_memory_edit",
);
const selectedLabel = answer?.selected_options?.[0];
selectedValue = selectedLabel
- ? options.find((opt) => opt.label === selectedLabel)?.value
+ ? options.find((o) => o.label === selectedLabel)?.value
: undefined;
} catch {
ctx.addItem(addInfo(ctx.sessionId, "Cancelled.", "i"));
return;
}
-
if (!selectedValue) {
ctx.addItem(addInfo(ctx.sessionId, "Cancelled.", "i"));
return;
}
-
- // Handle selected action
- if (selectedValue === ACTION_TOGGLE_MEMORY_ENABLED) {
- await toggleByKey(ctx, "memory_enabled");
- return;
- }
-
- if (selectedValue === ACTION_TOGGLE_AUTO_MEMORY) {
- await toggleByKey(ctx, "auto_memory_enabled");
- return;
- }
-
- if (selectedValue === ACTION_OPEN_AUTO_MEMORY_FOLDER) {
- const openPayload = await ctx.request<MemoryOpenResult>("memory.open", {
- project_dir: projectDir,
- });
- const targetDir = openPayload.coding_memory_dir || openPayload.auto_memory_dir;
- if (targetDir && ctx.openFolder) {
- ctx.openFolder(targetDir);
- ctx.addItem(addInfo(ctx.sessionId, "Opened memory folder", "m"));
- }
- return;
- }
-
- // Edit the selected memory file
await editMemoryByPath(ctx, selectedValue);
} catch (err) {
ctx.addItem(
@@ -728,6 +370,43 @@ async function showMemorySelector(ctx: import("../types.js").CommandContext): Pr
}
}
+/** 页签总页面:SelectList 模拟(无原生页签原语时的降级方案)。
+ * initialTab 指定时直达该页签;否则弹出页签选择器。 */
+const MEMORY_TABS = ["edit", "status", "toggle", "open"] as const;
+type MemoryTab = (typeof MEMORY_TABS)[number];
+
+async function showMemoryConsole(
+ ctx: import("../types.js").CommandContext,
+ initialTab?: MemoryTab,
+): Promise<void> {
+ if (initialTab === "edit") return editMemorySelector(ctx);
+ if (initialTab === "status") return showMemoryStatus(ctx);
+ if (initialTab === "toggle") return showToggleList(ctx);
+ if (initialTab === "open") return openMemoryDir(ctx);
+
+ // 无 initialTab:弹出页签选择器
+ try {
+ const [answer] = await ctx.askQuestions(
+ [
+ {
+ header: "Memory",
+ question: "Select a tab:",
+ options: MEMORY_TABS.map((t) => ({ label: t })),
+ },
+ ],
+ "local_command_memory_console",
+ );
+ const selected = answer?.selected_options?.[0] as MemoryTab | undefined;
+ if (!selected) {
+ ctx.addItem(addInfo(ctx.sessionId, "Cancelled.", "i"));
+ return;
+ }
+ await showMemoryConsole(ctx, selected);
+ } catch {
+ ctx.addItem(addInfo(ctx.sessionId, "Cancelled.", "i"));
+ }
+}
+
async function editMemory(
ctx: import("../types.js").CommandContext,
args: string,
@@ -735,7 +414,7 @@ async function editMemory(
const targetPath = args.trim();
if (!targetPath) {
- await showMemorySelector(ctx);
+ await editMemorySelector(ctx);
return;
}
@@ -750,6 +429,29 @@ async function editMemoryByPath(
const trustedDirs = ctx.getTrustedDirs();
const projectDir = ctx.getCurrentProjectDir();
+ // 把 display path(相对路径或 ~ 缩写)解析为绝对路径
+ // getDisplayPath 可能返回相对于 gitRoot/projectDir 的路径或 ~ 缩写
+ let resolvedPath = path;
+ if (path.startsWith("~/") || path === "~") {
+ resolvedPath = join(homedir(), path.slice(1));
+ } else if (!path.match(/^[A-Za-z]:[/\\]/) && !path.startsWith("/")) {
+ // 相对路径:尝试 join(projectDir, path),如果文件存在就用
+ const fromProject = join(projectDir, path);
+ if (existsSync(fromProject)) {
+ resolvedPath = fromProject;
+ } else {
+ // 尝试从 gitRoot 解析
+ const gitRoot = findGitRoot(projectDir);
+ if (gitRoot) {
+ const fromGit = join(gitRoot, path);
+ if (existsSync(fromGit)) {
+ resolvedPath = fromGit;
+ }
+ }
+ }
+ }
+ path = resolvedPath;
+
// 后端 _validate_edit_path 只白名单 project_dir 单层,会拒绝编辑 projectDir
// 祖先目录里的 JIUWENSWARM.md / JIUWENSWARM.local.md。这类文件是合法的
// project memory(前端 discoverMemoryFilesFromFs 已识别并列入选择器),
@@ -802,7 +504,8 @@ async function editMemoryByPath(
});
if (!payload.editable) {
- ctx.addItem(addError(ctx.sessionId, `Cannot edit: ${path} — path not in allowed memory directories.`));
+ const reason = payload.reason ?? "path not in allowed memory directories";
+ ctx.addItem(addError(ctx.sessionId, `Cannot edit: ${path} — ${reason}.`));
return;
}
@@ -856,11 +559,14 @@ async function showMemoryStatus(
items.push({ label: "Current Mode", value: payload.current_mode });
items.push({ label: "Storage Mode", value: payload.storage_mode });
items.push({ label: "Engine", value: payload.engine });
- items.push({ label: "Enabled", value: payload.enabled ? "✓ on" : "✗ off" });
- items.push({ label: "Proactive", value: payload.proactive ? "✓ on" : "✗ off" });
- items.push({ label: "Forbidden Filter", value: payload.forbidden_enabled ? "✓ on" : "✗ off" });
- if (payload.index) {
+ // 开关值行:镜像当前 mode 的 toggle 集合(registry 单一数据源)
+ for (const t of togglesForMode(mode)) {
+ items.push({ label: t.label, value: t.readValue(payload) ? "✓ on" : "✗ off" });
+ }
+
+ // Index / FTS5 / Vector / Cache:仅 agent mode(code mode 不走 agent 记忆引擎)
+ if (modeCategory(mode) === "agent" && payload.index) {
items.push({ label: "Index Available", value: payload.index.available ? "✓" : "✗" });
items.push({ label: "Embedding Provider", value: payload.index.provider ?? "N/A" });
items.push({ label: "Embedding Model", value: payload.index.model ?? "N/A" });
@@ -903,7 +609,8 @@ async function showMemoryStatus(
}
}
- if (payload.coding_memory) {
+ // Coding Memory 统计:仅 code mode
+ if (modeCategory(mode) === "code" && payload.coding_memory) {
items.push({
label: "Coding Memory Files",
value: String(payload.coding_memory.files_count),
@@ -920,7 +627,8 @@ async function showMemoryStatus(
}
}
- if (payload.auto_memory) {
+ // Auto Memory 统计:仅 agent mode
+ if (modeCategory(mode) === "agent" && payload.auto_memory) {
items.push({
label: "Auto Memory Files",
value: String(payload.auto_memory.files_count),
@@ -958,18 +666,62 @@ async function showMemoryStatus(
}
}
-const TOGGLE_KEYS = [
+// ---- MemoryActionRegistry: 单一数据源(按 mode 过滤)----
+// 消除 TOGGLE_KEYS(4) 与 toggle completion(3) 漂移;开关集合按 mode 自适应。
+// agent mode: memory_enabled / memory_proactive / memory_forbidden_enabled
+// code mode: memory_enabled / auto_coding_memory / memory_forbidden_enabled
+
+type MemoryModeCategory = "agent" | "code";
+
+interface ToggleDef {
+ key: string;
+ label: string;
+ modes: MemoryModeCategory[];
+ getConfigPath: (mode: string) => string;
+ readValue: (payload: MemoryStatusResult) => boolean;
+}
+
+const TOGGLE_DEFS: ToggleDef[] = [
{
key: "memory_enabled",
- label: "Enabled",
- getConfigPath: (mode: string) =>
+ label: "Memory",
+ modes: ["agent", "code"],
+ getConfigPath: (mode) =>
mode === "code" ? "modes.code.memory.enabled" : `modes.agent.${mode}.memory.enabled`,
+ readValue: (p) => p.enabled,
+ },
+ {
+ key: "memory_proactive",
+ label: "Proactive memory",
+ modes: ["agent"],
+ getConfigPath: (mode) => `modes.agent.${mode}.memory.is_proactive`,
+ readValue: (p) => p.proactive,
+ },
+ {
+ key: "auto_coding_memory",
+ label: "Auto coding memory",
+ modes: ["code"],
+ getConfigPath: () => "modes.code.memory.auto_coding_memory",
+ readValue: (p) => p.auto_coding_memory ?? false,
+ },
+ {
+ key: "memory_forbidden_enabled",
+ label: "Forbidden filter",
+ modes: ["agent", "code"],
+ getConfigPath: () => "memory.forbidden_memory_definition.enabled",
+ readValue: (p) => p.forbidden_enabled,
},
- { key: "memory_proactive", label: "Proactive", getConfigPath: (mode: string) => `modes.agent.${mode}.memory.is_proactive` },
- { key: "memory_forbidden_enabled", label: "Forbidden Filter", getConfigPath: () => "memory.forbidden_memory_definition.enabled" },
- { key: "auto_memory_enabled", label: "Auto Memory", getConfigPath: () => "auto_memory_enabled" },
];
+function modeCategory(shortMode: string): MemoryModeCategory {
+ return shortMode === "code" ? "code" : "agent";
+}
+
+function togglesForMode(shortMode: string): ToggleDef[] {
+ const cat = modeCategory(shortMode);
+ return TOGGLE_DEFS.filter((t) => t.modes.includes(cat));
+}
+
async function toggleMemory(
ctx: import("../types.js").CommandContext,
args: string,
@@ -993,14 +745,8 @@ async function showToggleList(
mode,
});
- const items = TOGGLE_KEYS.map((t) => {
- let current: boolean;
- if (t.key === "memory_enabled") current = payload.enabled;
- else if (t.key === "memory_proactive") current = payload.proactive;
- else if (t.key === "memory_forbidden_enabled") current = payload.forbidden_enabled;
- else if (t.key === "auto_memory_enabled") current = payload.auto_memory_enabled;
- else current = false;
-
+ const items = togglesForMode(mode).map((t) => {
+ const current = t.readValue(payload);
return {
label: t.key,
value: `${t.label} ${current ? "✓ on" : "✗ off"}`,
@@ -1034,7 +780,9 @@ async function toggleByKey(
ctx: import("../types.js").CommandContext,
key: string,
): Promise<void> {
- const validKeys = TOGGLE_KEYS.map((t) => t.key);
+ const mode = modeToShort(ctx.mode);
+ const defs = togglesForMode(mode);
+ const validKeys = defs.map((t) => t.key);
if (!validKeys.includes(key)) {
ctx.addItem(
addError(ctx.sessionId, `Unknown toggle key: ${key}. Valid keys: ${validKeys.join(", ")}`),
@@ -1042,14 +790,13 @@ async function toggleByKey(
return;
}
- const mode = modeToShort(ctx.mode);
try {
const payload = await ctx.request<MemoryToggleResult>("memory.toggle", {
key,
mode,
});
- const label = TOGGLE_KEYS.find((t) => t.key === key)?.label ?? key;
+ const label = defs.find((t) => t.key === key)?.label ?? key;
ctx.addItem(
addInfo(
ctx.sessionId,
@@ -1066,168 +813,73 @@ async function toggleByKey(
async function openMemoryDir(
ctx: import("../types.js").CommandContext,
-): Promise<void> {
- try {
- const payload = await ctx.request<MemoryOpenResult>("memory.open", {});
-
- const items: { label: string; value: string }[] = [];
- items.push({ label: "Memory Dir", value: payload.memory_dir });
- items.push({ label: "Project Dir", value: payload.project_memory_dir });
- if (payload.project_dir) {
- items.push({ label: "User Project Dir", value: payload.project_dir });
- }
- if (payload.coding_memory_dir) {
- items.push({ label: "Coding Memory Dir", value: payload.coding_memory_dir });
- }
- if (payload.auto_memory_dir) {
- items.push({ label: "Auto Memory Dir", value: payload.auto_memory_dir });
- }
-
- ctx.addItem(
- makeItem(ctx.sessionId, "info", "Memory Directories", "m", {
- view: "kv",
- title: "Memory Open",
- items,
- }),
- );
-
- ctx.addItem(
- addInfo(
- ctx.sessionId,
- `Open with: open ${payload.memory_dir} (macOS) | xdg-open ${payload.memory_dir} (Linux)`,
- "i",
- ),
- );
- } catch (err) {
- ctx.addItem(
- addError(ctx.sessionId, `Failed to get memory directories: ${err instanceof Error ? err.message : String(err)}`),
- );
- }
-}
-
-const OPEN_FOLDER_PREFIX = "__open_folder__";
-
-async function showAutoMemoryInteractive(
- ctx: import("../types.js").CommandContext,
): Promise<void> {
const mode = modeToShort(ctx.mode);
- const workspaceDir = ctx.getWorkspaceDir() || "";
- const projectDir = ctx.getCurrentProjectDir() || workspaceDir;
-
+ const cat = modeCategory(mode);
try {
- // Get memory status and files
- const statusPayload = await ctx.request<MemoryStatusResult>("memory.status", {
- detailed: true,
- mode,
+ const payload = await ctx.request<MemoryOpenResult>("memory.open", {
+ project_dir: ctx.getCurrentProjectDir() || undefined,
});
- const listPayload = await ctx.request<{ files: MemoryFile[] }>("memory.list", {
- mode,
- include_project: true,
- project_dir: projectDir,
- });
-
- const autoMemoryEnabled = statusPayload.auto_memory_enabled ?? false;
- const files = listPayload.files ?? [];
-
- // Build memory file options (Project and User memory)
- const projectMemoryPath = join(projectDir, "JIUWENSWARM.md");
- const userMemoryPath = join(workspaceDir, "JIUWENSWARM.local.md");
-
- const hasProjectMemory = files.some(
- (f) => f.path === projectMemoryPath || f.relative_path === "JIUWENSWARM.md",
- );
- const hasUserMemory = files.some(
- (f) => f.path === userMemoryPath || f.relative_path === "JIUWENSWARM.local.md",
- );
-
- // Add memory file options
- const memoryOptions: { label: string; description: string; value: string }[] = [];
-
- // Project memory
- memoryOptions.push({
- label: "Project memory",
- value: projectMemoryPath,
- description: hasProjectMemory ? `Saved in ./JIUWENSWARM.md` : "Saved in ./JIUWENSWARM.md (new)",
- });
-
- // User memory (local)
- memoryOptions.push({
- label: "User memory",
- value: userMemoryPath,
- description: hasUserMemory ? "Saved in ./JIUWENSWARM.local.md" : "Saved in ./JIUWENSWARM.local.md (new)",
- });
-
- // Add open folder option at the bottom (only when auto-memory enabled)
- if (autoMemoryEnabled) {
- memoryOptions.push({
- label: "Open auto-memory folder",
- value: `${OPEN_FOLDER_PREFIX}auto`,
- description: "",
- });
+ // 按 mode 过滤目录:agent 显 Memory Dir(auto memory);code 显 Coding Memory Dir
+ const options: { label: string; description?: string; value: string }[] = [];
+ if (cat === "agent") {
+ options.push({ label: "Memory Dir", value: payload.memory_dir });
+ }
+ if (cat === "code" && payload.coding_memory_dir) {
+ options.push({ label: "Coding Memory Dir", value: payload.coding_memory_dir });
+ }
+ options.push({ label: "Project Dir", value: payload.project_memory_dir });
+ if (payload.project_dir) {
+ options.push({ label: "User Project Dir", value: payload.project_dir });
}
-
- // Build toggle option at the top - align with Claude Code format: "Auto-memory: on/off"
- const toggleOption: { label: string; description: string; value: string } = {
- label: `Auto-memory: ${autoMemoryEnabled ? "on" : "off"}`,
- value: "__toggle__",
- description: "Press Enter to toggle",
- };
-
- // Combine all options: toggle at top, then files, then open folder
- const allOptions = [toggleOption, ...memoryOptions];
let selectedValue: string | undefined;
try {
const [answer] = await ctx.askQuestions(
[
{
- header: "Memory",
- question: "Select an action:",
- options: allOptions.map((opt) => ({
- label: opt.label,
- description: opt.description,
- })),
+ header: "Memory open",
+ question: "Select a directory to open:",
+ options: options.map((o) => ({ label: o.label, description: o.value })),
},
],
- "local_command_memory",
+ "local_command_memory_open",
);
- selectedValue = answer?.selected_options?.[0]
- ? allOptions.find((opt) => opt.label === answer.selected_options[0])?.value
+ const selectedLabel = answer?.selected_options?.[0];
+ selectedValue = selectedLabel
+ ? options.find((o) => o.label === selectedLabel)?.value
: undefined;
} catch {
- ctx.addItem(addInfo(ctx.sessionId, "Cancelled Memory interaction.", "i"));
+ ctx.addItem(addInfo(ctx.sessionId, "Cancelled.", "i"));
return;
}
-
if (!selectedValue) {
- ctx.addItem(addInfo(ctx.sessionId, "Cancelled Memory interaction.", "i"));
+ ctx.addItem(addInfo(ctx.sessionId, "Cancelled.", "i"));
return;
}
- // Handle selected action
- if (selectedValue === "__toggle__") {
- await toggleByKey(ctx, "auto_memory_enabled");
- } else if (selectedValue.startsWith(OPEN_FOLDER_PREFIX)) {
- // Open coding memory folder in system file explorer (unified with Auto Memory)
- const openPayload = await ctx.request<MemoryOpenResult>("memory.open", {
- project_dir: projectDir,
- });
- // Use coding_memory_dir as the unified memory location
- const targetDir = openPayload.coding_memory_dir || openPayload.auto_memory_dir;
- if (targetDir && ctx.openFolder) {
- ctx.openFolder(targetDir);
- ctx.addItem(
- addInfo(ctx.sessionId, "Opened memory folder", "m"),
- );
- }
+ // 优先调系统文件管理器打开;不支持时显示可复制路径 + 平台命令提示
+ if (ctx.openFolder) {
+ ctx.openFolder(selectedValue);
+ ctx.addItem(addInfo(ctx.sessionId, `Opened memory folder: ${selectedValue}`, "m"));
} else {
- // Edit the selected memory file
- await editMemoryByPath(ctx, selectedValue);
+ const cmd = process.platform === "win32"
+ ? `explorer "${selectedValue}"`
+ : process.platform === "darwin"
+ ? `open "${selectedValue}"`
+ : `xdg-open "${selectedValue}"`;
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ `Cannot open directly. Path: ${selectedValue}\nOpen with: ${cmd}`,
+ "i",
+ ),
+ );
}
} catch (err) {
ctx.addItem(
- addError(ctx.sessionId, `Failed to show Memory interface: ${err instanceof Error ? err.message : String(err)}`),
+ addError(ctx.sessionId, `Failed to get memory directories: ${err instanceof Error ? err.message : String(err)}`),
);
}
}
@@ -1237,28 +889,19 @@ export function createMemoryCommand(): SlashCommand {
name: "memory",
altNames: ["mem"],
description: "Manage memory settings and files (Auto-memory, edit, toggle, open)",
- usage: "/memory [list|edit|status|toggle|open] [args]",
+ usage: "/memory [edit|status|toggle|open] [args]",
example: "/memory",
kind: CommandKind.BUILT_IN,
takesArgs: true,
action: async (ctx) => {
- await showMemorySelector(ctx);
+ // 无参 → 弹出页签选择器(edit/status/toggle/open);
+ // 子命令 /memory <sub> 由各自 subCommand 直达对应页签。
+ await showMemoryConsole(ctx);
},
completion: async () => {
- return ["list", "edit", "status", "toggle", "open"];
+ return ["edit", "status", "toggle", "open"];
},
subCommands: [
- {
- name: "list",
- description: "List all memory files",
- usage: "/memory list",
- example: "/memory list",
- kind: CommandKind.BUILT_IN,
- takesArgs: false,
- action: async (ctx) => {
- await listMemory(ctx);
- },
- },
{
name: "edit",
description: "Edit a memory file (interactive selection if no path given)",
@@ -1269,7 +912,25 @@ export function createMemoryCommand(): SlashCommand {
action: async (ctx, args) => {
await editMemory(ctx, args);
},
- completion: async () => ["memory/MEMORY.md", "coding_memory/MEMORY.md"],
+ completion: async (ctx) => {
+ // 动态列规则文件(不含运行时记忆,后者只读),只返回存在的文件,去重
+ // 路径用 getDisplayPath 展示(与 edit 页签一致)
+ try {
+ const { files, projectDir } = await collectOrderedMemoryFiles(ctx, ctx.mode);
+ const seen = new Set<string>();
+ return files
+ .filter((f) => f.exists)
+ .map((f) => getDisplayPath(f.path, projectDir))
+ .filter((p) => {
+ const key = p.toLowerCase().replace(/\\/g, "/");
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+ } catch {
+ return [];
+ }
+ },
},
{
name: "status",
@@ -1292,7 +953,7 @@ export function createMemoryCommand(): SlashCommand {
action: async (ctx, args) => {
await toggleMemory(ctx, args);
},
- completion: async () => ["memory_enabled", "memory_proactive", "memory_forbidden_enabled"],
+ completion: async (ctx) => togglesForMode(modeToShort(ctx.mode)).map((t) => t.key),
},
{
name: "open",
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/actions.ts b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/actions.ts
index 54ab8a9da6..3464bb2c29 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/actions.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/actions.ts
@@ -14,6 +14,7 @@ export const KEYBINDING_CONTEXTS = [
"TeamPanel",
"SwarmWorkflows",
"StatusView",
+ "MemoryView",
"ResumeList",
"Overlay",
] as const;
@@ -28,6 +29,7 @@ export const KEYBINDING_CONTEXT_DESCRIPTIONS: Record<KeybindingContextName, stri
TeamPanel: "When the team panel is open",
SwarmWorkflows: "When the swarm workflows view is open",
StatusView: "When the status/config view is open (tab navigation only)",
+ MemoryView: "When the memory console view is open (tab navigation only)",
ResumeList: "When the resume session picker is open",
Overlay:
"Generic close binding for MCP detail/tool sub-views (list navigation itself is owned by pi-tui)",
@@ -78,6 +80,11 @@ export const KEYBINDING_ACTIONS = [
"status:close",
"status:prevTab",
"status:nextTab",
+ // MemoryView (tab navigation; list navigation + Enter actions stay hardcoded)
+ "memory:close",
+ "memory:prevTab",
+ "memory:nextTab",
+ "memory:toggleFullPath",
// ResumeList (session picker shortcuts; list nav + search text entry, plus the
// rename-input and preview sub-states, stay hardcoded).
"resume:close",
@@ -126,6 +133,10 @@ export const KEYBINDING_ACTION_DESCRIPTIONS: Record<KeybindingAction, string> =
"status:close": "关闭状态/配置视图",
"status:prevTab": "上一个标签页",
"status:nextTab": "下一个标签页",
+ "memory:close": "关闭记忆控制台",
+ "memory:prevTab": "上一个页签",
+ "memory:nextTab": "下一个页签",
+ "memory:toggleFullPath": "list/edit 页签切换显示完整路径",
"resume:close": "关闭会话选择器(先清空搜索)",
"resume:toggleAllProjects": "切换“所有项目”过滤",
"resume:toggleBranchFilter": "切换分支过滤",
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/defaultBindings.ts b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/defaultBindings.ts
index 5160d9a06b..c91b408342 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/defaultBindings.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/defaultBindings.ts
@@ -88,6 +88,15 @@ export const DEFAULT_BINDINGS: KeybindingBlock[] = [
right: "status:nextTab",
},
},
+ {
+ context: "MemoryView",
+ bindings: {
+ escape: "memory:close",
+ left: "memory:prevTab",
+ right: "memory:nextTab",
+ "ctrl+o": "memory:toggleFullPath",
+ },
+ },
{
context: "ResumeList",
bindings: {
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/utils/editor.ts b/jiuwenswarm/channels/tui/frontend/src/core/utils/editor.ts
index e5fbc5786f..ca60612787 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/utils/editor.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/utils/editor.ts
@@ -1,4 +1,4 @@
-import { spawnSync, type SpawnSyncOptions, type SpawnSyncReturns } from "node:child_process";
+import { spawn, spawnSync, type SpawnOptions, type SpawnSyncOptions, type SpawnSyncReturns } from "node:child_process";
import { basename } from "node:path";
import { existsSync, mkdirSync } from "node:fs";
import type { TUI } from "@mariozechner/pi-tui";
@@ -70,63 +70,160 @@ function spawnFailed(result: SpawnSyncReturns<string | Buffer>): boolean {
return result.status !== 0 || result.error != null;
}
-export function openFileInEditor(tui: TUI, filePath: string): void {
+/**
+ * Open a file in the user's external editor.
+ *
+ * For GUI editors (notepad, VS Code, Sublime, etc.): spawns the editor
+ * detached and non-blocking — the TUI keeps running, no stop/start cycle.
+ * This avoids the race condition where tui.stop()/tui.start() could leave
+ * stdin in a bad state (Kitty protocol query interference, buffered data
+ * from the editor process, etc.).
+ *
+ * For terminal editors (vi, nano): uses spawnSync (blocking) with proper
+ * alt-screen switching and tui.stop()/tui.start() — the TUI is suspended
+ * while the editor takes over the terminal.
+ *
+ * @param onExit Called when the editor process exits (GUI editors only).
+ * Terminal editors call onExit synchronously after tui.start().
+ */
+export function openFileInEditor(tui: TUI, filePath: string, onExit?: () => void): void {
const editor = getExternalEditor();
- const { cmd, args } = parseEditorCommand(editor);
const gui = isGuiEditor(editor);
+ if (gui) {
+ spawnGuiEditorDetached(editor, filePath, onExit);
+ return;
+ }
+
+ // Terminal editor: spawnSync + tui.stop/start (blocks until editor exits)
+ const { cmd, args } = parseEditorCommand(editor);
+
tui.stop();
try {
- if (!gui) {
- process.stdout.write("\x1b[?1049h");
- process.stdout.write("\x1b[2J\x1b[H");
- process.stdout.write("\x1b[?25h");
+ // Enter alt screen + clear + show cursor.
+ // The editor (vim/nano) will manage its own alt screen on top of ours.
+ process.stdout.write("\x1b[?1049h\x1b[2J\x1b[H\x1b[?25h");
- if (process.stdin.setRawMode) {
- process.stdin.setRawMode(false);
- }
- process.stdin.resume();
+ if (process.stdin.setRawMode) {
+ process.stdin.setRawMode(false);
}
+ process.stdin.resume();
- const result = spawnEditor(cmd, args, filePath);
+ const result = spawnEditorSync(cmd, args, filePath);
if (spawnFailed(result)) {
- spawnFallback(filePath);
+ spawnFallbackSync(filePath);
}
} finally {
- if (!gui) {
- process.stdout.write("\x1b[?1049l");
+ // ── Terminal recovery (mirrors claude-code's exitAlternateScreen) ──
+ //
+ // Terminal editors (vim, nano, less) write smcup/rmcup (?1049h/?1049l).
+ // On exit, vim's rmcup drops us back to the MAIN screen — our alt screen
+ // is already gone. Simply writing ?1049l is a no-op here.
+ //
+ // We re-enter alt screen → clear → exit alt screen, which gives a clean
+ // main screen without wiping the user's scrollback. This is the key fix
+ // for the "Win10 + git bash + vim → TUI stuck" bug.
+ process.stdout.write("\x1b[?1049h\x1b[2J\x1b[H\x1b[?1049l\x1b[?25l");
+
+ // Drain any buffered stdin data left by the editor process.
+ // vim may leave escape sequences in the stdin buffer; if these reach
+ // tui.start()'s Kitty protocol query handler, they can confuse input
+ // parsing and cause the TUI to appear frozen.
+ try {
+ while (process.stdin.read() !== null) {
+ // discard all buffered data
+ }
+ } catch {
+ // stdin not readable or already destroyed — ignore
}
tui.start();
tui.requestRender(true);
+ onExit?.();
}
}
-function spawnEditor(cmd: string, args: string[], filePath: string): SpawnSyncReturns<string | Buffer> {
+// ---------------------------------------------------------------------------
+// GUI editor: non-blocking detached spawn (TUI keeps running)
+// ---------------------------------------------------------------------------
+
+/**
+ * Spawn a GUI editor detached from the parent process.
+ *
+ * The editor runs in its own window/process. The TUI event loop keeps
+ * running, so the user can interact with the TUI while editing.
+ *
+ * On exit, the optional `onExit` callback is called (best-effort — for
+ * editors launched via shell wrappers like `code.cmd` on Windows, the
+ * exit event may fire immediately when the wrapper exits, not when the
+ * actual editor window closes).
+ */
+function spawnGuiEditorDetached(editor: string, filePath: string, onExit?: () => void): void {
+ const detachedOpts: SpawnOptions = { detached: true, stdio: "ignore" };
+
+ let child;
+
+ if (process.platform === "win32") {
+ // Windows: keep "start /wait" in the command.
+ // "start /wait" is a cmd.exe builtin that makes the shell wait for the
+ // GUI editor to close. Without it, cmd.exe would exit immediately after
+ // launching the GUI app, and child.on('exit') would fire prematurely.
+ // With it, the spawned cmd.exe process stays alive until the editor closes,
+ // so the exit event fires at the right time.
+ //
+ // We use shell: true because:
+ // - "start" is a cmd.exe builtin (not an executable)
+ // - .cmd/.bat editors like code.cmd need shell resolution
+ child = spawn(`${editor} "${filePath}"`, { ...detachedOpts, shell: true });
+ } else {
+ // POSIX: spawn the editor directly (no shell).
+ // Strip --wait/-w flags — they're for blocking spawnSync, not needed
+ // for non-blocking spawn. We detect exit via child.on('exit').
+ const parts = editor.split(/\s+/).filter((p) => p && p !== "-w" && p !== "--wait");
+ const cmd = parts[0];
+ const fullArgs = [...parts.slice(1), filePath];
+ child = spawn(cmd, fullArgs, detachedOpts);
+ }
+
+ child.on("error", () => {
+ // Spawn failed — try fallback
+ spawnFallbackAsync(filePath, onExit);
+ });
+
+ if (onExit) {
+ child.on("exit", () => {
+ onExit();
+ });
+ }
+
+ // unref() so the TUI process can exit without waiting for the editor
+ child.unref();
+}
+
+// ---------------------------------------------------------------------------
+// Terminal editor: synchronous spawn (blocking)
+// ---------------------------------------------------------------------------
+
+function spawnEditorSync(cmd: string, args: string[], filePath: string): SpawnSyncReturns<string | Buffer> {
const spawnOptions: SpawnSyncOptions = { stdio: "inherit" };
const fullArgs = [...args, filePath];
if (process.platform === "win32") {
if (cmd === "start") {
- // Windows start command: start /wait "title" program args
- // An empty title "" prevents the first quoted arg from being treated as window title
- // /wait must remain unquoted — it's a flag, not an argument
const waitFlag = fullArgs[0] === "/wait" ? "/wait " : "";
const programArgs = waitFlag ? fullArgs.slice(1) : fullArgs;
const quoted = programArgs.map((a) => `"${a}"`).join(" ");
return spawnSync(`start ${waitFlag}"" ${quoted}`, { ...spawnOptions, shell: true });
}
- // shell: true required for .cmd/.bat files (code.cmd, cursor.cmd)
const quoted = fullArgs.map((a) => `"${a}"`).join(" ");
return spawnSync(`${cmd} ${quoted}`, { ...spawnOptions, shell: true });
}
- // POSIX: direct argv spawn — no shell, prevents command injection
return spawnSync(cmd, fullArgs, spawnOptions);
}
-function spawnFallback(filePath: string): SpawnSyncReturns<string | Buffer> {
+function spawnFallbackSync(filePath: string): SpawnSyncReturns<string | Buffer> {
const spawnOptions: SpawnSyncOptions = { stdio: "inherit" };
if (process.platform === "win32") {
@@ -136,6 +233,29 @@ function spawnFallback(filePath: string): SpawnSyncReturns<string | Buffer> {
return spawnSync("vi", [filePath], spawnOptions);
}
+function spawnFallbackAsync(filePath: string, onExit?: () => void): void {
+ if (process.platform === "win32") {
+ // Use "start /wait" so cmd.exe waits for notepad to close
+ // (without /wait, cmd.exe exits immediately for GUI apps)
+ const child = spawn(`start /wait "" notepad "${filePath}"`, {
+ detached: true,
+ stdio: "ignore",
+ shell: true,
+ });
+ if (onExit) child.on("exit", onExit);
+ child.unref();
+ return;
+ }
+
+ const child = spawn("vi", [filePath], { detached: true, stdio: "ignore" });
+ if (onExit) child.on("exit", onExit);
+ child.unref();
+}
+
+// ---------------------------------------------------------------------------
+// Folder opening (file explorer)
+// ---------------------------------------------------------------------------
+
/**
* Open a folder in the system file explorer (not an editor).
* - Windows: explorer
@@ -155,13 +275,10 @@ export function openFolderInExplorer(folderPath: string): void {
}
if (process.platform === "win32") {
- // Windows: use explorer to open folder
spawnSync(`explorer "${folderPath}"`, { ...spawnOptions, shell: true });
} else if (process.platform === "darwin") {
- // macOS: use open -R to reveal in Finder
spawnSync("open", ["-R", folderPath], spawnOptions);
} else {
- // Linux: use xdg-open
spawnSync("xdg-open", [folderPath], spawnOptions);
}
-}
\ No newline at end of file
+}
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
index 83ca90c54c..d6e96712e3 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
@@ -52,6 +52,7 @@ import {
import type { ConfigItemSchema } from "../core/commands/builtins/config.js";
import type { McpListItem, McpListPayload } from "../core/commands/builtins/mcp.js";
import { buildModeAutocompleteItems } from "../core/commands/builtins/mode.js";
+import { MemoryViewController, type MemoryViewTab } from "./memory-view.js";
import { PIPELINE_VALUES, PIPELINE_OPTIONS, INTERVAL_VALUES, INTERVAL_OPTIONS, FLAG_OPTIONS } from "../core/commands/builtins/auto-harness.js";
import { isTeamMode } from "../core/modes.js";
import {
@@ -666,6 +667,7 @@ class ComposerAutocompleteProvider implements AutocompleteProvider {
constructor(
private readonly inner: AutocompleteProvider,
private readonly cwd: string,
+ private readonly memoryArgCompletion?: (sub: string) => Promise<{ label: string; description: string }[]>,
) {}
async getSuggestions(
@@ -683,8 +685,57 @@ class ComposerAutocompleteProvider implements AutocompleteProvider {
return null;
}
+ // /memory edit|toggle + 空格:直接调用 completion 获取文件/key 列表,绕过 CombinedAutocompleteProvider
+ const memArgMatch = textBeforeCursor.match(/^\/memory\s+(edit|toggle)\s+(\S*)$/);
+ if (memArgMatch && this.memoryArgCompletion) {
+ try {
+ const sub = memArgMatch[1];
+ const argPrefix = memArgMatch[2].toLowerCase();
+ const items = await this.memoryArgCompletion(sub);
+ const filtered = argPrefix
+ ? items.filter((item) => item.label.toLowerCase().startsWith(argPrefix))
+ : items;
+ if (filtered.length > 0) {
+ return {
+ items: filtered.map((item) => ({
+ label: item.label,
+ description: item.description,
+ value: item.label,
+ usage: "",
+ example: "",
+ })),
+ prefix: argPrefix,
+ };
+ }
+ } catch { /* ignore */ }
+ return null;
+ }
+
+ // /memory edit|toggle(无尾随空格):抑制 inner provider 的文件补全。
+ // inner provider 会以 "edit" 为 prefix 返回文件列表,applyCompletion 时会把
+ // "edit" 替换成文件名 → /memory JIUWENSWARM.local.md(丢失子命令)。
+ // 用户需要先输入空格,才走上面的 memArgMatch 路径正确展示文件列表。
+ if (/^\/memory\s+(edit|toggle)$/.test(textBeforeCursor)) {
+ return null;
+ }
+
const innerResult = await this.inner.getSuggestions(lines, cursorLine, cursorCol, options);
- if (innerResult) return innerResult;
+ if (innerResult) {
+ // 对命令参数候选项做前缀过滤:取最后一个空格后的文本作为参数前缀
+ const lastSpaceIdx = textBeforeCursor.lastIndexOf(" ");
+ if (lastSpaceIdx >= 0) {
+ const argPrefix = textBeforeCursor.slice(lastSpaceIdx + 1).toLowerCase();
+ if (argPrefix) {
+ const filtered = innerResult.items.filter((item) =>
+ item.label.toLowerCase().startsWith(argPrefix)
+ );
+ if (filtered.length > 0 && filtered.length < innerResult.items.length) {
+ return { ...innerResult, items: filtered };
+ }
+ }
+ }
+ return innerResult;
+ }
if (options.signal.aborted) return null;
@@ -713,6 +764,7 @@ class ComposerAutocompleteProvider implements AutocompleteProvider {
const result = this.inner.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
+ // @ 文件补全后自动加空格
if (prefix.startsWith("@") && !result.lines[result.cursorLine]?.endsWith(" ")) {
const line = result.lines[result.cursorLine] ?? "";
const newLines = [...result.lines];
@@ -1269,6 +1321,7 @@ export class AppScreen implements Component, Focusable {
private themeList: ThemeListState | null = null;
private configEditorState: ConfigEditorState | null = null;
private statusViewState: StatusViewState | null = null;
+ private mvController: MemoryViewController | null = null;
private swarmWorkflowsViewState: SwarmWorkflowsViewState | null = null;
private startupPromptList: SelectList | null = null;
private todosCollapsed = false;
@@ -1339,6 +1392,22 @@ export class AppScreen implements Component, Focusable {
this.transientNotice = null;
}
this.tui.requestRender();
+
+ // pi-tui 的 Editor 只对字母数字字符自动触发 autocomplete,不处理空格。
+ // 这导致 /memory edit<空格> 后不会自动展示文件列表——用户必须手按 Tab。
+ // 在 slash 命令上下文中输入空格时手动触发,补全 provider 会自行决定是否展示。
+ const ed = this.editor as unknown as {
+ autocompleteState?: unknown;
+ tryTriggerAutocomplete?: () => void;
+ state?: { cursorLine: number; cursorCol: number; lines: string[] };
+ };
+ if (!ed.autocompleteState && ed.tryTriggerAutocomplete && ed.state) {
+ const line = ed.state.lines[ed.state.cursorLine] ?? "";
+ const before = line.slice(0, ed.state.cursorCol);
+ if (before.trimStart().startsWith("/") && before.endsWith(" ")) {
+ ed.tryTriggerAutocomplete();
+ }
+ }
};
this.editor.onSubmit = async (value) => {
void await this.handleSubmit(value);
@@ -2061,7 +2130,8 @@ export class AppScreen implements Component, Focusable {
this.themeList !== null ||
this.swarmWorkflowsViewState !== null ||
this.configEditorState !== null ||
- this.diffViewerState !== null;
+ this.diffViewerState !== null ||
+ this.mvController !== null && this.mvController.isOpen;
if (
!pendingQuestion &&
@@ -2158,19 +2228,26 @@ export class AppScreen implements Component, Focusable {
}
if (hasInput) {
// 第一次 Esc(输入框非空):进入待清空状态并显示提示
- this.escClearPending = true;
- this.transientNotice = "Press Esc again to clear input";
- if (this.transientNoticeTimer) {
- clearTimeout(this.transientNoticeTimer);
- }
- this.transientNoticeTimer = setTimeout(() => {
- this.escClearPending = false;
- this.transientNoticeTimer = null;
- this.transientNotice = null;
+ // 例外:/memory edit 和 /memory toggle 跳过双击清空,让 editor 处理 Esc 取消 completion 提示
+ const trimmed = this.editor.getText().trimStart();
+ const skipEscClear = trimmed === "/memory edit" || trimmed === "/memory toggle";
+ if (skipEscClear) {
+ // 不拦截,继续后续流程让 editor.handleInput 处理
+ } else {
+ this.escClearPending = true;
+ this.transientNotice = "Press Esc again to clear input";
+ if (this.transientNoticeTimer) {
+ clearTimeout(this.transientNoticeTimer);
+ }
+ this.transientNoticeTimer = setTimeout(() => {
+ this.escClearPending = false;
+ this.transientNoticeTimer = null;
+ this.transientNotice = null;
+ this.tui.requestRender();
+ }, 3000);
this.tui.requestRender();
- }, 3000);
- this.tui.requestRender();
- return;
+ return;
+ }
}
// 输入框为空:不响应,继续后续流程
}
@@ -2215,7 +2292,7 @@ export class AppScreen implements Component, Focusable {
const skipGlobalMainScreenKeys = hasOverlay || this.showTeamPanel;
const allowGlobalAction =
!skipGlobalMainScreenKeys ||
- globalAction === "app:toggleTranscript" ||
+ (globalAction === "app:toggleTranscript" && !(this.mvController?.isOpen ?? false)) ||
(this.showTeamPanel && !hasOverlay && globalAction === "app:toggleTeamPanel");
let handled = false;
if (allowGlobalAction) {
@@ -2505,6 +2582,12 @@ export class AppScreen implements Component, Focusable {
return;
}
+ // MemoryView 键盘:←/→ 切页签,Esc 关闭,Ctrl+O 切全路径,其余交给 SelectList
+ if (!snapshot.pendingQuestion && this.mvController?.isOpen) {
+ this.mvController.handleInput(data);
+ return;
+ }
+
if (!snapshot.pendingQuestion && this.configEditorState !== null) {
this.handleConfigEditorInput(data);
this.tui.requestRender();
@@ -2663,7 +2746,8 @@ export class AppScreen implements Component, Focusable {
hideEditorForInlinePlanReject ||
this.resumeSessionList !== null ||
this.state.isHelpVisible() ||
- this.modelList !== null;
+ this.modelList !== null ||
+ (this.mvController?.isOpen ?? false);
const editorLines = hideMainEditor
? []
: this.applySlashCommandHint(this.editor.render(width), width);
@@ -2671,6 +2755,7 @@ export class AppScreen implements Component, Focusable {
const questionLines = [
...this.buildStartupPromptLines(width),
...this.buildStatusViewLines(width),
+ ...(this.mvController?.isOpen ? this.mvController.buildLines(width) : []),
...(!this.statusViewState ? this.buildConfigEditorLines(width) : []),
...this.buildResumeSessionListLines(width),
...this.buildModelListLines(width),
@@ -3036,6 +3121,18 @@ export class AppScreen implements Component, Focusable {
await this.openStatusView(tab);
return;
}
+ // /memory(无参)及 /memory <edit|status|toggle|open>(无后续参数)
+ // 打开 MemoryView 页签控制台;带参数的形式(/memory edit <path>、/memory toggle <key>)
+ // 不匹配,继续走命令分发器(保留 completion)。
+ const memMatch = text.match(/^\/memory(?:\s+(edit|status|toggle|open))?$/);
+ if (memMatch) {
+ this.editor.addToHistory(text);
+ this.editor.setText("");
+ this.state.addItem(addCommandEcho(snapshot.sessionId, text));
+ const memTab = (memMatch[1] as MemoryViewTab | undefined) ?? "edit";
+ await this.ensureMvController().open(memTab);
+ return;
+ }
if (/^\/theme\s*$/.test(text)) {
this.editor.addToHistory(text);
this.editor.setText("");
@@ -6374,6 +6471,18 @@ export class AppScreen implements Component, Focusable {
this.tui.requestRender();
}
+ // ──────────────────────────── MemoryView ────────────────────────────
+
+ /** 懒初始化 MemoryViewController(复用实例,状态在 controller 内部管理) */
+ private ensureMvController(): MemoryViewController {
+ if (!this.mvController) {
+ this.mvController = new MemoryViewController(this.state, this.tui);
+ }
+ return this.mvController;
+ }
+
+ // MemoryView 的具体逻辑已提取到 ui/memory-view.ts(MemoryViewController)
+
private clearPastedTextState(): void {
this.cancelPastedTextStateClear();
this.pastedTextById.clear();
@@ -6735,6 +6844,10 @@ export class AppScreen implements Component, Focusable {
resolveFdBinary(),
),
getCurrentCwd() || process.cwd(),
+ // /memory edit|toggle 参数 completion 回调(绕过 CombinedAutocompleteProvider 的子命令名候选项)
+ async (sub: string) => {
+ return this.ensureMvController().getMemoryCompletions(sub);
+ },
);
}
@@ -6846,6 +6959,25 @@ export class AppScreen implements Component, Focusable {
}));
}
+ // 子命令名补全:当输入前缀未精确匹配任何子命令时,
+ // 提示以该前缀开头的子命令名(如 /memory edi → edit)。
+ // 输入为空时提示全部子命令(如 /memory <space>)。
+ if (matchedPath.length === 0 && command.subCommands?.length) {
+ const prefix = trimmed.toLowerCase();
+ const matchingSubs = command.subCommands.filter(
+ (sub) => !prefix || sub.name.toLowerCase().startsWith(prefix),
+ );
+ if (matchingSubs.length > 0) {
+ return matchingSubs.map((sub) => ({
+ label: sub.name,
+ description: sub.description ?? "",
+ value: sub.name,
+ usage: sub.usage,
+ example: sub.example,
+ }));
+ }
+ }
+
return null;
}
: undefined,
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/memory-view.ts b/jiuwenswarm/channels/tui/frontend/src/ui/memory-view.ts
new file mode 100644
index 0000000000..d2ffe7fbb2
--- /dev/null
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/memory-view.ts
@@ -0,0 +1,495 @@
+// ── MemoryView:页签式记忆控制台(从 app-screen.ts 提取)──
+//
+// 管理 /memory 的四个页签(edit/status/toggle/open)的交互、渲染和状态。
+// app-screen.ts 通过持有 MemoryViewController 实例并委托调用其方法来使用。
+
+import * as fs from "node:fs";
+import * as path from "node:path";
+import { type TUI, type SelectItem, SelectList } from "@mariozechner/pi-tui";
+import { addInfo } from "../core/commands/helpers.js";
+import type { CliPiAppState } from "../app-state.js";
+import { openFileInEditor as openInExternalEditor, openFolderInExplorer } from "../core/utils/editor.js";
+import { collectOrderedMemoryFiles, type MemoryFile } from "../core/commands/builtins/memory.js";
+import { getDisplayPath } from "../core/commands/builtins/memory-path-utils.js";
+import { palette, selectListTheme } from "./theme.js";
+import { padToWidth } from "./rendering/text.js";
+import { resolveAction } from "../core/keybindings/resolver.js";
+
+// ── 类型定义 ──
+
+export type MemoryViewTab = "edit" | "status" | "toggle" | "open";
+
+export interface MVFile {
+ path: string;
+ relative_path: string;
+ kind: string;
+ exists: boolean;
+ size: number;
+ mtime: number;
+ lines: number;
+}
+
+export interface MVStatus {
+ current_mode: string;
+ enabled: boolean;
+ proactive: boolean;
+ forbidden_enabled: boolean;
+ auto_memory_enabled: boolean;
+ auto_coding_memory?: boolean | null;
+ storage_mode: string;
+ engine: string;
+ project_memory?: { files_count: number; total_chars: number; max_chars: number; project_dir?: string };
+ coding_memory?: { files_count: number; total_chars: number; dir: string };
+ auto_memory?: { files_count: number; total_chars: number; dir: string };
+ external_memory?: { provider: string; enabled: boolean };
+}
+
+export interface MVOpen {
+ memory_dir: string;
+ project_memory_dir: string;
+ project_dir?: string;
+ coding_memory_dir?: string;
+ auto_memory_dir?: string;
+}
+
+interface MemoryViewState {
+ tab: MemoryViewTab;
+ list: SelectList;
+ mode: string;
+ files: MVFile[];
+ statusPayload: MVStatus | null;
+ openPayload: MVOpen | null;
+ projectDir: string;
+ gitRoot: string | null;
+ userMemoryPath: string;
+ loading?: boolean;
+}
+
+// ── Controller ──
+
+export class MemoryViewController {
+ private state: MemoryViewState | null = null;
+ private showFullPath = false;
+ /** 底部通知行:显示最新一次操作结果,新覆盖旧 */
+ private statusMessage: string | null = null;
+
+ constructor(
+ private appState: CliPiAppState,
+ private tui: TUI,
+ ) {}
+
+ // ── 状态查询 ──
+
+ get isOpen(): boolean {
+ return this.state !== null;
+ }
+
+ // ── 补全 ──
+
+ /**
+ * 获取 /memory edit|toggle 参数补全列表(带类型标识)。
+ * edit:返回文件路径 + 记忆类型(Project/Local/User memory)
+ * toggle:返回开关 key + 中文描述
+ */
+ async getMemoryCompletions(sub: string): Promise<{ label: string; description: string }[]> {
+ const ctx = this.appState.getCommandContext();
+ const mode = this.shortMode(ctx.mode ?? "code.normal");
+
+ if (sub === "edit") {
+ const { files, projectDir, userMemoryPath } = await collectOrderedMemoryFiles(ctx, mode).catch(() => ({
+ files: [] as MemoryFile[],
+ userMemoryPath: "",
+ projectDir: "",
+ }));
+ const lower = (p: string) => (process.platform === "win32" ? p.toLowerCase() : p);
+ return files
+ .filter((f) => f.exists)
+ .map((f) => {
+ const dp = getDisplayPath(f.path, projectDir);
+ const p = f.path.replace(/\\/g, "/");
+ let desc = "";
+ if (lower(f.path) === lower(userMemoryPath)) {
+ desc = "User memory";
+ } else if (
+ f.kind === "project"
+ && p.endsWith("JIUWENSWARM.md")
+ && !p.endsWith("JIUWENSWARM.local.md")
+ && !p.endsWith(".jiuwen/JIUWENSWARM.md")
+ ) {
+ desc = "Project memory";
+ } else if (f.kind === "local" && p.endsWith("JIUWENSWARM.local.md")) {
+ desc = "Local memory";
+ } else {
+ desc = f.kind;
+ }
+ return { label: dp, description: desc };
+ });
+ }
+
+ if (sub === "toggle") {
+ return this.togglesForMode(mode).map((t) => ({
+ label: t.key,
+ description: t.desc,
+ }));
+ }
+
+ return [];
+ }
+
+ // ── 打开 / 关闭 ──
+
+ async open(tab?: MemoryViewTab): Promise<void> {
+ this.showFullPath = false;
+ this.statusMessage = null;
+ const ctx = this.appState.getCommandContext();
+ const fullMode = ctx.mode ?? "code.normal";
+ const projectDir = ctx.getCurrentProjectDir() || process.cwd();
+ const initialTab: MemoryViewTab = tab ?? "edit";
+
+ // 立即展示 loading 状态,不阻塞用户界面
+ this.state = {
+ tab: initialTab,
+ list: new SelectList([], 1, selectListTheme),
+ mode: fullMode,
+ files: [],
+ statusPayload: null,
+ openPayload: null,
+ projectDir,
+ gitRoot: null,
+ userMemoryPath: "",
+ loading: true,
+ };
+ this.tui.requestRender();
+
+ // 异步加载数据(首次可能需等待后端 Agent 创建完成)
+ const [collected, statusPayload, openPayload] = await Promise.all([
+ collectOrderedMemoryFiles(ctx, this.shortMode(fullMode)).catch(() => ({
+ files: [] as MemoryFile[],
+ userMemoryPath: "",
+ gitRoot: null as string | null,
+ projectDir,
+ })),
+ this.appState.request<MVStatus>("memory.status", { detailed: true, mode: this.shortMode(fullMode) }).catch(() => null),
+ this.appState.request<MVOpen>("memory.open", { project_dir: projectDir }).catch(() => null),
+ ]);
+
+ if (!this.state) return; // 用户可能已关闭
+
+ const files = collected.files;
+ this.state = {
+ tab: initialTab,
+ list: this.buildTabState(initialTab, files, statusPayload, openPayload, fullMode, projectDir, collected.gitRoot, collected.userMemoryPath),
+ mode: fullMode,
+ files,
+ statusPayload,
+ openPayload,
+ projectDir,
+ gitRoot: collected.gitRoot,
+ userMemoryPath: collected.userMemoryPath,
+ loading: false,
+ };
+ this.tui.requestRender();
+ }
+
+ close(): void {
+ const sessionId = this.appState.getSnapshot().sessionId;
+ this.appState.addItem(addInfo(sessionId, "Memory console dismissed", "✓"));
+ this.state = null;
+ this.tui.requestRender();
+ }
+
+ // ── 键盘输入 ──
+
+ /** 处理 MemoryView 上下文的键盘输入,返回 true 表示已消费。 */
+ handleInput(data: string): boolean {
+ if (this.state === null) return false;
+ // loading 时只允许 Esc 关闭
+ if (this.state.loading) {
+ if (resolveAction("MemoryView", data) === "memory:close") {
+ this.close();
+ }
+ return true;
+ }
+ switch (resolveAction("MemoryView", data)) {
+ case "memory:close":
+ this.close();
+ return true;
+ case "memory:prevTab":
+ this.switchTab(-1);
+ return true;
+ case "memory:nextTab":
+ this.switchTab(1);
+ return true;
+ case "memory:toggleFullPath":
+ this.showFullPath = !this.showFullPath;
+ this.rebuildTabList();
+ return true;
+ default:
+ break;
+ }
+ this.state.list.handleInput(data);
+ this.tui.requestRender();
+ return true;
+ }
+
+ // ── 渲染 ──
+
+ buildLines(width: number): string[] {
+ if (!this.state) return [];
+ const lines: string[] = [];
+ lines.push(...this.renderTabBar(width));
+ lines.push(padToWidth(palette.text.dim("─".repeat(width)), width));
+ if (this.state.loading) {
+ lines.push(padToWidth(palette.text.dim(" Loading..."), width));
+ } else if (this.state.tab === "status") {
+ const items = this.buildStatusItems(this.state.statusPayload, this.state.mode);
+ for (const item of items) {
+ const label = item.label.padEnd(20);
+ lines.push(padToWidth(` ${label}${item.description ?? ""}`, width));
+ }
+ } else {
+ lines.push(...this.state.list.render(width));
+ }
+ // 底部通知行:显示最新操作结果(新覆盖旧),仅在 toggle 页签有消息时显示
+ if (this.statusMessage) {
+ lines.push(padToWidth(palette.status.warning(this.statusMessage), width));
+ }
+ const hint =
+ this.state.tab === "edit"
+ ? "←/→ tabs · Enter edit file · Ctrl+O toggle full path · Esc close"
+ : this.state.tab === "status"
+ ? "←/→ tabs · Esc close"
+ : this.state.tab === "toggle"
+ ? "←/→ tabs · Enter toggle · Esc close"
+ : "←/→ tabs · Enter open folder · Ctrl+O toggle full path · Esc close";
+ lines.push(padToWidth(palette.text.dim(hint), width));
+ return lines;
+ }
+
+ // ── 内部方法 ──
+
+ private renderTabBar(width: number): string[] {
+ const tabs: MemoryViewTab[] = ["edit", "status", "toggle", "open"];
+ const labels = tabs.map((t) => (t === this.state!.tab ? `[${t}]` : t));
+ const activeIndex = tabs.indexOf(this.state!.tab);
+ const parts: string[] = [];
+ for (let i = 0; i < labels.length; i++) {
+ const seg = labels[i];
+ parts.push(i === activeIndex ? palette.status.warning(seg) : palette.text.dim(seg));
+ if (i < labels.length - 1) parts.push(palette.text.dim(" "));
+ }
+ return [padToWidth(parts.join(""), width)];
+ }
+
+ private switchTab(direction: -1 | 1): void {
+ if (!this.state) return;
+ const tabs: MemoryViewTab[] = ["edit", "status", "toggle", "open"];
+ const current = tabs.indexOf(this.state.tab);
+ const next = (current + direction + tabs.length) % tabs.length;
+ this.state.tab = tabs[next];
+ this.showFullPath = false;
+ this.statusMessage = null;
+ this.rebuildTabList();
+ this.tui.requestRender();
+ }
+
+ private rebuildTabList(): void {
+ if (!this.state) return;
+ const s = this.state;
+ this.state.list = this.buildTabState(
+ s.tab,
+ s.files,
+ s.statusPayload,
+ s.openPayload,
+ s.mode,
+ s.projectDir,
+ s.gitRoot,
+ s.userMemoryPath,
+ );
+ this.tui.requestRender();
+ }
+
+ private buildTabState(
+ tab: MemoryViewTab,
+ files: MVFile[],
+ status: MVStatus | null,
+ openP: MVOpen | null,
+ mode: string,
+ projectDir: string,
+ gitRoot: string | null,
+ _userMemoryPath: string,
+ ): SelectList {
+ const items =
+ tab === "edit"
+ ? this.buildEditItems(files, projectDir, gitRoot)
+ : tab === "status"
+ ? this.buildStatusItems(status, mode)
+ : tab === "toggle"
+ ? this.buildToggleItems(status, mode)
+ : this.buildOpenItems(openP, mode);
+
+ const list = new SelectList(items, Math.min(Math.max(items.length, 1), 12), selectListTheme, {
+ minPrimaryColumnWidth: 20,
+ maxPrimaryColumnWidth: 50,
+ });
+ list.onSelect = (item: SelectItem) => {
+ this.handleSelect(tab, item, mode, projectDir);
+ };
+ list.onCancel = () => {
+ this.close();
+ };
+ return list;
+ }
+
+ private buildEditItems(files: MVFile[], projectDir: string, gitRoot: string | null): SelectItem[] {
+ return files.map((f) => {
+ const label = this.fileLabel(f);
+ const dp = this.showFullPath ? f.path.replace(/\\/g, "/") : getDisplayPath(f.path, projectDir, gitRoot);
+ const isGitTracked = gitRoot && f.kind !== "local" && f.kind !== "user";
+ const desc = label === dp ? undefined : isGitTracked ? `Checked in at ${dp}` : `Saved in ${dp}`;
+ return { value: f.path, label, description: desc };
+ });
+ }
+
+ private buildStatusItems(status: MVStatus | null, mode: string): SelectItem[] {
+ if (!status) return [{ value: "__display__", label: "Failed to load status", description: "" }];
+ const cat = this.modeCategory(mode);
+ const items: SelectItem[] = [
+ { value: "__display__", label: "Engine", description: `${status.engine} (${status.storage_mode})` },
+ ];
+ for (const t of this.togglesForMode(mode)) {
+ items.push({ value: "__display__", label: t.label, description: t.read(status) ? "✓ on" : "✗ off" });
+ }
+ if (cat === "agent") {
+ if (status.auto_memory)
+ items.push({ value: "__display__", label: "Auto Memory", description: `${status.auto_memory.files_count} files · ${status.auto_memory.total_chars} chars` });
+ } else {
+ if (status.coding_memory)
+ items.push({ value: "__display__", label: "Coding Memory", description: `${status.coding_memory.files_count} files · ${status.coding_memory.total_chars} chars` });
+ }
+ if (status.project_memory)
+ items.push({ value: "__display__", label: "Project Memory", description: `${status.project_memory.files_count} files · ${status.project_memory.total_chars} chars` });
+ if (status.external_memory)
+ items.push({ value: "__display__", label: "External Memory", description: `${status.external_memory.provider} ${status.external_memory.enabled ? "✓" : "✗"}` });
+ return items;
+ }
+
+ private buildToggleItems(status: MVStatus | null, mode: string): SelectItem[] {
+ if (!status) return [{ value: "__display__", label: "Failed to load status", description: "" }];
+ const toggles = this.togglesForMode(mode);
+ const maxKeyLen = Math.max(...toggles.map((t) => t.key.length));
+ return toggles.map((t) => ({
+ value: t.key,
+ label: t.key.padEnd(maxKeyLen),
+ description: `${t.read(status) ? "✓ on " : "✗ off"} ${t.desc}`,
+ }));
+ }
+
+ private buildOpenItems(openP: MVOpen | null, mode: string): SelectItem[] {
+ if (!openP) return [{ value: "__display__", label: "Failed to load directories", description: "" }];
+ const cat = this.modeCategory(mode);
+ const projectDir = this.state?.projectDir ?? "";
+ const gitRoot = this.state?.gitRoot ?? null;
+ const fmt = (p: string) => (this.showFullPath ? p : getDisplayPath(p, projectDir, gitRoot));
+ const items: SelectItem[] = [];
+ if (cat === "agent") items.push({ value: openP.memory_dir, label: "Memory Dir", description: fmt(openP.memory_dir) });
+ if (cat === "code" && openP.coding_memory_dir) items.push({ value: openP.coding_memory_dir, label: "Coding Memory Dir", description: fmt(openP.coding_memory_dir) });
+ items.push({ value: openP.project_memory_dir, label: "Project Dir", description: fmt(openP.project_memory_dir) });
+ if (openP.project_dir) items.push({ value: openP.project_dir, label: "User Project Dir", description: fmt(openP.project_dir) });
+ return items;
+ }
+
+ private async handleSelect(tab: MemoryViewTab, item: SelectItem, mode: string, _projectDir: string): Promise<void> {
+ if (tab === "edit" && item.value && item.value !== "__display__") {
+ const filePath = item.value;
+ if (!fs.existsSync(filePath)) {
+ try {
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, "", "utf-8");
+ } catch {
+ // 创建失败仍尝试打开,让编辑器报错
+ }
+ }
+ // GUI 编辑器:异步 spawn,TUI 不阻塞,编辑器关闭后通过 onExit 回调刷新
+ // 终端编辑器:spawnSync 阻塞,tui.start() 后同步调用 onExit
+ openInExternalEditor(this.tui, filePath, () => {
+ this.refreshFiles();
+ });
+ return;
+ }
+ if (tab === "toggle" && item.value && item.value !== "__display__") {
+ const key = item.value;
+ const before = this.state?.statusPayload;
+ const oldVal = before ? this.togglesForMode(mode).find((t) => t.key === key)?.read(before) ?? false : false;
+ try {
+ await this.appState.request("memory.toggle", { key, mode: this.shortMode(mode) });
+ const statusPayload = await this.appState.request<MVStatus>("memory.status", { mode: this.shortMode(mode) }).catch(() => null);
+ const newVal = statusPayload ? this.togglesForMode(mode).find((t) => t.key === key)?.read(statusPayload) ?? oldVal : oldVal;
+ const label = this.togglesForMode(mode).find((t) => t.key === key)?.label ?? key;
+ // 底部通知行:新覆盖旧,不累积到 transcript
+ this.statusMessage = `${label}: ${oldVal ? "on" : "off"} → ${newVal ? "on" : "off"} (restart session to apply)`;
+ if (this.state) {
+ this.state.statusPayload = statusPayload;
+ this.rebuildTabList();
+ }
+ this.tui.requestRender();
+ } catch (err) {
+ this.statusMessage = `Toggle failed: ${err instanceof Error ? err.message : String(err)}`;
+ this.tui.requestRender();
+ }
+ return;
+ }
+ if (tab === "open" && item.value && item.value !== "__display__") {
+ openFolderInExplorer(item.value);
+ return;
+ }
+ // status 只读,无操作
+ }
+
+ /** 编辑器关闭后重新加载文件列表,刷新 edit 页签的元信息 */
+ private async refreshFiles(): Promise<void> {
+ const s = this.state;
+ if (!s) return;
+ const ctx = this.appState.getCommandContext();
+ const collected = await collectOrderedMemoryFiles(ctx, this.shortMode(s.mode)).catch(() => ({
+ files: [] as MemoryFile[],
+ userMemoryPath: s.userMemoryPath,
+ gitRoot: s.gitRoot,
+ projectDir: s.projectDir,
+ }));
+ s.files = collected.files;
+ if (collected.gitRoot) s.gitRoot = collected.gitRoot;
+ s.userMemoryPath = collected.userMemoryPath;
+ this.rebuildTabList();
+ }
+
+ // ── 辅助方法 ──
+
+ private shortMode(mode: string): string {
+ if (mode.startsWith("code")) return "code";
+ return mode.replace("agent.", "");
+ }
+
+ private modeCategory(mode: string): "agent" | "code" {
+ return this.shortMode(mode) === "code" ? "code" : "agent";
+ }
+
+ private togglesForMode(mode: string): { key: string; label: string; desc: string; read: (s: MVStatus) => boolean }[] {
+ const cat = this.modeCategory(mode);
+ const all = [
+ { key: "memory_enabled", label: "Memory", cats: ["agent", "code"], desc: "记忆功能总开关", read: (s: MVStatus) => s.enabled },
+ { key: "memory_proactive", label: "Proactive memory", cats: ["agent"], desc: "对话中自动搜索和记录", read: (s: MVStatus) => s.proactive },
+ { key: "auto_coding_memory", label: "Auto coding memory", cats: ["code"], desc: "每轮对话后自动提取记忆(需总开关开启)", read: (s: MVStatus) => s.auto_coding_memory ?? false },
+ { key: "memory_forbidden_enabled", label: "Forbidden filter", cats: ["agent", "code"], desc: "过滤敏感信息", read: (s: MVStatus) => s.forbidden_enabled },
+ ];
+ return all.filter((t) => t.cats.includes(cat)).map((t) => ({ key: t.key, label: t.label, desc: t.desc, read: t.read }));
+ }
+
+ private fileLabel(f: MVFile): string {
+ const p = f.path.replace(/\\/g, "/");
+ if (f.kind === "user") return "User memory";
+ if (f.kind === "local") return "Local memory";
+ if (f.kind === "project" && p.endsWith("JIUWENSWARM.md") && !p.endsWith("JIUWENSWARM.local.md")) return "Project memory";
+ return f.relative_path || p;
+ }
+}
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index 4595fe8c9a..91dca78051 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -149,21 +149,6 @@ def set_config(config):
yaml.safe_dump(config, f, allow_unicode=True, sort_keys=False)
-def is_auto_memory_enabled() -> bool:
- """Check if auto-memory feature is enabled in config.
-
- Returns:
- True if auto_memory_enabled is True in config.yaml, False otherwise.
- Defaults to True if not configured.
- """
- try:
- config = get_config()
- return bool(config.get("auto_memory_enabled", False))
- except Exception:
- # Default to True if config cannot be read
- return True
-
-
def _get_bool_env(value: str | None) -> bool | None:
if value is None:
return None
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 6db4146cb5..eaf3bc0c32 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -27,7 +27,7 @@ from jiuwenswarm.server.runtime.agent_adapter.agent_adapters import (
create_adapter,
resolve_sdk_choice,
)
-from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode, is_memory_enabled
+from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode, is_auto_memory_enabled, is_memory_enabled
from jiuwenswarm.server.runtime.session.session_history import (
append_compact_history_records,
append_history_record,
@@ -35,7 +35,7 @@ from jiuwenswarm.server.runtime.session.session_history import (
from jiuwenswarm.server.runtime.session.session_manager import SessionManager
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
from jiuwenswarm.server.utils.utils import is_team_params
-from jiuwenswarm.common.config import get_config, is_auto_memory_enabled
+from jiuwenswarm.common.config import get_config
from jiuwenswarm.extensions.registry import ExtensionRegistry
from jiuwenswarm.common.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk
from jiuwenswarm.extensions.hook_event import AgentServerHookEvents
@@ -1726,7 +1726,7 @@ class JiuWenSwarm:
# 需要 auto_memory_enabled 和 memory.enabled 都为 true 才触发
mode = request.params.get("mode", "code") if isinstance(request.params, dict) else "code"
config = get_config()
- if is_auto_memory_enabled() and is_memory_enabled(mode, config):
+ if is_auto_memory_enabled(mode, config) and is_memory_enabled(mode, config):
_trigger_auto_memory_extraction(adapter, request, session_id, is_stream=False)
return result
@@ -2306,7 +2306,7 @@ class JiuWenSwarm:
# 需要 auto_memory_enabled 和 memory.enabled 都为 true 才触发
mode = request.params.get("mode", "code") if isinstance(request.params, dict) else "code"
config = get_config()
- if is_auto_memory_enabled() and is_memory_enabled(mode, config):
+ if is_auto_memory_enabled(mode, config) and is_memory_enabled(mode, config):
_trigger_auto_memory_extraction(adapter, request, session_id, is_stream=True)
yield AgentResponseChunk(