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): 修复auto memory报错
jingjinduoe04d44acfe2e
diff --git a/docs/README.md b/docs/README.mdindex bab0204953..b8001d3e1f 100644--- a/docs/README.md+++ b/docs/README.md@@ -160,8 +160,8 @@</tr><tr><td width="22%"><strong>记忆</strong></td>- <td width="28%"><a href="zh/记忆.md">记忆</a> / <a href="zh/编码记忆.md">编码记忆</a> / <a href="zh/经验记忆.md">经验记忆</a></td>- <td width="50%">支持长短期记忆管理、编码场景下的专属记忆沉淀,以及任务经验的检索、复用与持续积累。</td>+ <td width="28%"><a href="zh/记忆.md">记忆</a> / <a href="zh/自动记忆.md">自动记忆</a> / <a href="zh/编码记忆.md">编码记忆</a> / <a href="zh/经验记忆.md">经验记忆</a></td>+ <td width="50%">支持长短期记忆管理、对话后自动提取记忆、编码场景下的专属记忆沉淀,以及任务经验的检索、复用与持续积累。</td></tr><tr><td width="22%"><strong>TUI 模式</strong></td>diff --git a/docs/README_EN.md b/docs/README_EN.mdindex db26cd06b2..9dbe822bfb 100644--- a/docs/README_EN.md+++ b/docs/README_EN.md@@ -160,8 +160,8 @@ This page collects common JiuwenSwarm usage instructions, feature documentation,</tr><tr><td width="22%"><strong>Memory</strong></td>- <td width="28%"><a href="en/Memory.md">Memory</a> / <a href="en/CodingMemory.md">Coding Memory</a> / <a href="en/TaskMemory.md">Task Memory</a></td>- <td width="50%">Supports short-term and long-term memory management, code-specific memory accumulation, and task experience retrieval, reuse, and continuous accumulation.</td>+ <td width="28%"><a href="en/Memory.md">Memory</a> / <a href="en/AutoMemory.md">Auto Memory</a> / <a href="en/CodingMemory.md">Coding Memory</a> / <a href="en/TaskMemory.md">Task Memory</a></td>+ <td width="50%">Supports short-term and long-term memory management, automatic post-conversation memory extraction, code-specific memory accumulation, and task experience retrieval, reuse, and continuous accumulation.</td></tr><tr><td width="22%"><strong>TUI Mode</strong></td>diff --git a/docs/en/AutoMemory.md b/docs/en/AutoMemory.mdnew file mode 100644index 0000000000..617270ea9b--- /dev/null+++ b/docs/en/AutoMemory.md@@ -0,0 +1,132 @@+# Auto Memory++Auto Memory is JiuwenSwarm's post-conversation memory extraction feature. After each conversation ends, it automatically analyzes the dialogue content, extracts information worth retaining long-term, and writes it to memory files with project-isolated storage.++---++## Overview++- **Automatic Extraction**: After conversation ends, the system automatically analyzes and extracts key information without user intervention+- **Project Isolation**: Each project stores memory independently, avoiding cross-project information confusion+- **Configurable Toggle**: Flexible enable/disable via config file or TUI command++---++## Enabling++### Config File++Set `auto_memory_enabled` in `config.yaml`:++```yaml+# Auto Memory: Automatically extract memories after conversation ends, stored per-project+auto_memory_enabled: true+```++### TUI Command++Toggle 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+```++In the interactive interface, select the `Auto-memory: on/off` option to toggle.++---++## Storage Path++Auto Memory stores memories isolated by project path:++```+~/.jiuwenswarm/projects/{sanitized-project-path}/memory/+├── MEMORY.md # Long-term memory+├── YYYY-MM-DD.md # Daily memory+└── consolidated_{hash}.md # Consolidated memory (optional)+```++Where `{sanitized-project-path}` is the project path after safety processing (special characters replaced with underscores).++---++## How It Works++### Extraction Timing++Auto Memory triggers at the following moments:++1. **Conversation End**: After each user-Agent conversation ends, the system checks if memory extraction is needed+2. **Non-streaming Request**: Triggers after `process_message` returns result+3. **Streaming Request**: Triggers after `process_message_stream` completes++### Extracted Content++The system analyzes conversation content through a sub-Agent, extracting the following types of information:++| Information Type | Description | Example |+|-----------------|-------------|---------|+| User Preferences | Preferences or habits explicitly expressed by user | "User prefers pytest framework" |+| Project Decisions | Technical choices, architecture decisions | "Project adopts FastAPI as backend framework" |+| Key Facts | Facts that need long-term retention | "Database connection string stored in .env file" |+| Problem Solutions | Debugging process, root causes | "Login failure caused by JWT expiry time misconfiguration" |++### Extraction Flow++```mermaid+flowchart TD+ A[Conversation End] --> B{auto_memory_enabled?}+ B -->|No| C[Skip Extraction]+ B -->|Yes| D[Create Extraction Sub-Agent]+ D --> E[Analyze Conversation History]+ E --> F[Extract Key Information]+ F --> G[Write to Memory Files]+ G --> H[Cleanup Resources]+```++---++## Configuration++| Config Item | Description | Default Value |+|------------|-------------|---------------|+| `auto_memory_enabled` | Whether to enable auto memory extraction | `false` |++---++## TUI Interaction++### `/memory` Command++Enter `/memory` command in TUI to display memory management interface:++```+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+```++Select the `Auto-memory: on/off` row and press Enter to toggle auto memory.++---++## Notes++1. **First Enable**: After first enabling auto memory, restart the session for it to take effect+2. **Storage Space**: Long-term use accumulates memory files; recommend periodic cleanup of outdated content+3. **Sensitive Information**: System automatically filters passwords, API keys, etc. (via `memory.forbidden_memory_definition` config)+4. **Performance Impact**: Extraction runs asynchronously in background, does not affect conversation response speed++---++## See Also++- [Configuration](Configuration.md) — Config file details+- [Quick start (TUI)](Quickstart_tui.md) — TUI command usage\ No newline at end of filediff --git a/docs/en/SUMMARY.md b/docs/en/SUMMARY.mdindex b19fff972d..8bd4c9575c 100644--- a/docs/en/SUMMARY.md+++ b/docs/en/SUMMARY.md@@ -24,6 +24,7 @@- [Scheduled tasks](ScheduledTasks.md)- [Task planning](TaskPlanning.md)- [Memory](Memory.md)+ - [Auto Memory](AutoMemory.md)- [Task Memory](TaskMemory.md)- [Context compression & offload](ContextCompression.md)- [Coding Memory](CodingMemory.md)diff --git a/docs/zh/SUMMARY.md b/docs/zh/SUMMARY.mdindex e350941941..55652841c9 100644--- a/docs/zh/SUMMARY.md+++ b/docs/zh/SUMMARY.md@@ -27,6 +27,7 @@- [定时任务](定时任务.md)- [任务规划](任务规划.md)- [记忆系统](记忆.md)+ - [自动记忆](自动记忆.md)- [经验记忆](经验记忆.md)- [上下文压缩卸载](上下文压缩卸载.md)- [编码记忆](编码记忆.md)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"new file mode 100644index 0000000000..2a145872e0--- /dev/null+++ "b/docs/zh/\350\207\252\345\212\250\350\256\260\345\277\206.md"@@ -0,0 +1,132 @@+# 自动记忆(Auto Memory)++自动记忆是 JiuwenSwarm 的对话后记忆提取功能,在每次对话结束后自动分析对话内容,提取值得长期保留的信息并写入记忆文件,按项目隔离存储。++---++## 功能概述++- **自动提取**:对话结束后无需用户干预,系统自动分析并提取关键信息+- **项目隔离**:每个项目独立存储记忆,避免跨项目信息混淆+- **可配置开关**:通过配置文件或 TUI 命令灵活启用/禁用++---++## 启用方式++### 配置文件启用++在 `config.yaml` 中设置 `auto_memory_enabled`:++```yaml+# Auto Memory:对话结束后自动提取记忆,按项目隔离存储+auto_memory_enabled: true+```++### TUI 命令启用++在 TUI 终端中使用 `/memory` 命令切换:++```+/memory # 进入记忆管理界面+/memory toggle # 显示所有记忆开关+/memory toggle auto_memory_enabled # 切换自动记忆开关+```++在交互界面中,选择 `Auto-memory: on/off` 选项即可切换。++---++## 存储路径++自动记忆按项目路径隔离存储:++```+~/.jiuwenswarm/projects/{sanitized-project-path}/memory/+├── MEMORY.md # 长期记忆+├── YYYY-MM-DD.md # 每日记忆+└── consolidated_{hash}.md # 整合记忆(可选)+```++其中 `{sanitized-project-path}` 是项目路径经过安全处理后的字符串(替换特殊字符为下划线)。++---++## 工作机制++### 提取时机++自动记忆在以下时机触发:++1. **对话结束时**:每次用户与 Agent 的对话结束后,系统检查是否需要提取记忆+2. **非流式请求**:`process_message` 返回结果后触发+3. **流式请求**:`process_message_stream` 完成后触发++### 提取内容++系统通过子 Agent 分析对话内容,提取以下类型的信息:++| 信息类型 | 说明 | 示例 |+|----------|------|------|+| 用户偏好 | 用户明确表达的偏好或习惯 | "用户偏好使用 pytest 框架" |+| 项目决策 | 技术选型、架构决策 | "项目采用 FastAPI 作为后端框架" |+| 关键事实 | 需要长期记住的事实 | "数据库连接字符串存储在 .env 文件" |+| 问题解决 | 调试过程、问题根因 | "登录失败原因是 JWT 过期时间配置错误" |++### 提取流程++```mermaid+flowchart TD+ A[对话结束] --> B{auto_memory_enabled?}+ B -->|否| C[跳过提取]+ B -->|是| D[创建提取子Agent]+ D --> E[分析对话历史]+ E --> F[提取关键信息]+ F --> G[写入记忆文件]+ G --> H[清理资源]+```++---++## 配置说明++| 配置项 | 说明 | 默认值 |+|--------|------|--------|+| `auto_memory_enabled` | 是否启用自动记忆提取 | `false` |++---++## TUI 交互++### `/memory` 命令++在 TUI 中输入 `/memory` 命令,会显示记忆管理界面:++```+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+```++选择 `Auto-memory: on/off` 行并按 Enter,即可切换自动记忆开关。++---++## 注意事项++1. **首次启用**:首次启用自动记忆后,需要重启会话才能生效+2. **存储空间**:长期使用会积累记忆文件,建议定期清理过期内容+3. **敏感信息**:系统会自动过滤密码、API Key 等敏感信息(通过 `memory.forbidden_memory_definition` 配置)+4. **性能影响**:提取过程在后台异步执行,不影响对话响应速度++---++## 详见++- [配置信息](配置信息.md) — 配置文件详细说明+- [TUI 使用指南](TUI使用指南.md) — TUI 命令使用方法\ No newline at end of filediff --git a/jiuwenswarm/agents/harness/common/auto_memory/extract_memories.py b/jiuwenswarm/agents/harness/common/auto_memory/extract_memories.pyindex 367d98ac4c..f5e2f2e360 100644--- a/jiuwenswarm/agents/harness/common/auto_memory/extract_memories.py+++ b/jiuwenswarm/agents/harness/common/auto_memory/extract_memories.py@@ -120,7 +120,8 @@ def _convert_messages_to_base_messages(messages: list[dict[str, Any] | Any]) ->elif role == "system":converted.append(SystemMessage(content=str(content)))elif role == "tool":- converted.append(ToolMessage(content=str(content)))+ tool_call_id = msg.get("tool_call_id", "")+ converted.append(ToolMessage(content=str(content), tool_call_id=tool_call_id))else:# Fallback to user messageconverted.append(UserMessage(content=str(content)))diff --git a/jiuwenswarm/agents/harness/common/auto_memory/extraction_runner.py b/jiuwenswarm/agents/harness/common/auto_memory/extraction_runner.pyindex 3bd10f67ae..c83fa94729 100644--- a/jiuwenswarm/agents/harness/common/auto_memory/extraction_runner.py+++ b/jiuwenswarm/agents/harness/common/auto_memory/extraction_runner.py@@ -149,8 +149,7 @@ async def _create_memory_extraction_context(async def _execute_auto_memory_extraction(project_dir: str,session_id: str,- request: "AgentRequest",- context_engine: "ContextEngine | None" = None,+ messages: list | None = None,parent_agent: "AgentAdapter | None" = None,) -> None:"""Execute auto memory extraction in background.@@ -160,8 +159,7 @@ async def _execute_auto_memory_extraction(Args:project_dir: The project root path.session_id: The session ID.- request: The agent request.- context_engine: The context engine to retrieve conversation messages.+ messages: Pre-retrieved messages from session history.parent_agent: The parent AgentAdapter instance (for cache sharing, optional)."""# Import utility functions from extract_memories module@@ -187,30 +185,14 @@ async def _execute_auto_memory_extraction(logger.warning("[auto_memory] Skipped: project_dir is not a directory")return- # Get conversation messages from context engine+ # Use pre-retrieved messages from session historyhistory = []- if context_engine is None:- logger.warning("[auto_memory] context_engine is None, cannot retrieve messages")+ if messages is not None:+ logger.info("[auto_memory] Using pre-retrieved messages (%d messages)", len(messages))+ history = messageselse:- try:- context = context_engine.get_context(session_id=session_id)- if context is None:- logger.warning("[auto_memory] get_context returned None")- else:- raw_messages = list(context.get_messages())- logger.debug("[auto_memory] raw_messages count: %d", len(raw_messages))- # Convert to serializable format- for msg in raw_messages:- if hasattr(msg, "to_dict"):- history.append(msg.to_dict())- elif hasattr(msg, "model_dump"):- history.append(msg.model_dump())- elif isinstance(msg, dict):- history.append(msg)- else:- history.append({"role": getattr(msg, "role", "unknown"), "content": str(msg)})- except Exception as exc:- logger.warning("[auto_memory] Failed to get messages from context_engine: %s", exc)+ logger.warning("[auto_memory] No messages provided, cannot extract memories")+ returnif not history:logger.debug("[auto_memory] Skipped: no conversation messages found")@@ -261,8 +243,6 @@ async def _execute_auto_memory_extraction(# Run memory extraction with cache sharing mode# Cache Sharing: inherit parent's model, tools, message prefix for API cache hit- logger.info("[auto_memory] === USING CACHE SHARING MODE ===")- logger.debug("[auto_memory] parent_agent type: %s", type(parent_agent).__name__)await _run_memory_extraction_with_cache_sharing(memory_dir=memory_dir,prompt=prompt,diff --git a/jiuwenswarm/agents/harness/common/memory/config.py b/jiuwenswarm/agents/harness/common/memory/config.pyindex 7653b951b8..11239ddc31 100644--- a/jiuwenswarm/agents/harness/common/memory/config.py+++ b/jiuwenswarm/agents/harness/common/memory/config.py@@ -196,7 +196,7 @@ def _resolve_mode_memory(mode: str, config: Optional[Dict[str, Any]]) -> Dict[stAccepts several mode formats used across the codebase:- "agent.plan" / "agent.fast" -> modes.agent.plan / modes.agent.fast- "plan" / "fast" -> modes.agent.plan / modes.agent.fast- - "code" -> modes.code+ - "code" / "code.normal" -> modes.codeReturns {} when no block is found (callers treat missing as disabled)."""modes_cfg = (config or {}).get("modes", {}) if isinstance(config, dict) else {}@@ -206,9 +206,13 @@ def _resolve_mode_memory(mode: str, config: Optional[Dict[str, Any]]) -> Dict[sttoken = (mode or "").strip()if "." in token:top, sub = token.split(".", 1)- node = modes_cfg.get(top, {})- if isinstance(node, dict):- node = node.get(sub, {})+ # Special handling for "code.*" -> modes.code (ignore sub_mode)+ if top == "code":+ node = modes_cfg.get("code", {})+ else:+ node = modes_cfg.get(top, {})+ if isinstance(node, dict):+ node = node.get(sub, {})elif token == "code":node = modes_cfg.get("code", {})else:@@ -231,9 +235,17 @@ def is_memory_enabled(mode: str, config: Optional[Dict[str, Any]] = None) -> booArgs:config: Optional config dict. If provided, reads from it directly(avoids stale cache). Otherwise reads from config.yaml.++ Note:+ For 'code' mode, default is True (CodingMemoryRail was always mounted before).+ For agent modes (plan/fast), default is False."""try:- return bool(_resolve_mode_memory(mode, config).get("enabled", False))+ mem_cfg = _resolve_mode_memory(mode, config)+ # code 模式默认开启(之前 CodingMemoryRail 是固定挂载的)+ # agent 模式默认关闭+ default_value = True if mode == "code" else False+ return bool(mem_cfg.get("enabled", default_value))except Exception as e:logger.warning(f"Invalid memory config, disable memory, error: {e}")return Falsediff --git a/jiuwenswarm/agents/harness/common/memory_rpc.py b/jiuwenswarm/agents/harness/common/memory_rpc.pyindex 8c438ebb8c..fb2f21d260 100644--- a/jiuwenswarm/agents/harness/common/memory_rpc.py+++ b/jiuwenswarm/agents/harness/common/memory_rpc.py@@ -295,9 +295,9 @@ async def handle_memory_status(detailed = params.get("detailed", False)config = get_config()- code_mode = _is_code_mode(mode)- enabled = is_memory_enabled(mode, config) if not code_mode else True- proactive = is_proactive_memory(mode, config) if not code_mode else False+ # code 模式现在也有 memory.enabled 配置项,直接读取+ enabled = is_memory_enabled(mode, config)+ proactive = is_proactive_memory(mode, config)result: dict[str, Any] = {"current_mode": mode,@@ -471,9 +471,16 @@ def _update_mode_memory_config(mode: str, field: str, value: bool) -> None:data = _load_yaml_round_trip(_CONFIG_YAML_PATH)modes = data.setdefault("modes", {})- agent = modes.setdefault("agent", {})- mode_node = agent.setdefault(mode, {})- memory = mode_node.setdefault("memory", {})++ # code 模式写入 modes.code.memory,其他模式写入 modes.agent.<mode>.memory+ if _is_code_mode(mode):+ code_node = modes.setdefault("code", {})+ memory = code_node.setdefault("memory", {})+ else:+ agent = modes.setdefault("agent", {})+ mode_node = agent.setdefault(mode, {})+ memory = mode_node.setdefault("memory", {})+memory[field] = value_dump_yaml_round_trip(_CONFIG_YAML_PATH, data)diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.tsindex 287683c6a1..3ce0316c7a 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.ts@@ -481,6 +481,7 @@ async function listMemory(ctx: import("../types.js").CommandContext): Promise<vo* 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__";@@ -495,6 +496,7 @@ async function showMemorySelector(ctx: import("../types.js").CommandContext): Prctx.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@@ -584,22 +586,30 @@ async function showMemorySelector(ctx: import("../types.js").CommandContext): Pr// Build options — EXACTLY aligned with Claude Code's /memory display// Aligned with Claude Code format:- // 1. Auto-memory: on/off (toggle — always at top)- // 2. Project memory Checked in at ./CLAUDE.md- // 3. .claude/rules/git.md- // 4. User memory Saved in ~/.claude/CLAUDE.md- // 5. Open auto-memory folder (only when auto-memory is on)+ // 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. Auto-memory toggle — always at the top (aligned with Claude Code)+ // 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 endsoptions.push({label: `Auto-memory: ${autoMemoryEnabled ? "on" : "off"}`,description: "Press Enter to toggle",value: ACTION_TOGGLE_AUTO_MEMORY,});- // 2. Memory file entries+ // 3. Memory file entriesfor (const f of orderedFiles) {const filePathLower = filePathLowerFn(f.path);const displayPath = getDisplayPath(f.path, projectDir);@@ -665,6 +675,11 @@ async function showMemorySelector(ctx: import("../types.js").CommandContext): Pr}// 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;@@ -875,10 +890,15 @@ async function showMemoryStatus(}const TOGGLE_KEYS = [- { key: "memory_enabled", label: "Enabled", config_path: "modes.agent.<mode>.memory.enabled" },- { key: "memory_proactive", label: "Proactive", config_path: "modes.agent.<mode>.memory.is_proactive" },- { key: "memory_forbidden_enabled", label: "Forbidden Filter", config_path: "memory.forbidden_memory_definition.enabled" },- { key: "auto_memory_enabled", label: "Auto Memory", config_path: "auto_memory_enabled" },+ {+ key: "memory_enabled",+ label: "Enabled",+ getConfigPath: (mode: string) =>+ mode === "code" ? "modes.code.memory.enabled" : `modes.agent.${mode}.memory.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" },];async function toggleMemory(@@ -915,7 +935,7 @@ async function showToggleList(return {label: t.key,value: `${t.label} ${current ? "✓ on" : "✗ off"}`,- description: t.config_path,+ description: t.getConfigPath(mode),};});diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.pyindex d001cc2aaf..11264c45a7 100644--- a/jiuwenswarm/common/config.py+++ b/jiuwenswarm/common/config.py@@ -132,7 +132,7 @@ def is_auto_memory_enabled() -> bool:"""try:config = get_config()- return bool(config.get("auto_memory_enabled", True))+ return bool(config.get("auto_memory_enabled", False))except Exception:# Default to True if config cannot be readreturn Truediff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 5466bd4afa..e4a7f6796f 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -67,7 +67,7 @@ symphony:# Auto Memory:对话结束后自动提取记忆,按项目隔离存储# 存储路径:~/.jiuwenswarm/projects/{sanitized-project-path}/memory/# 类似 Claude Code 的 auto-memory 功能-auto_memory_enabled: true+auto_memory_enabled: false# 日志目录:~/.jiuwenswarm/agent/.logs/# gateway.log / channel.log / agent_server.log 按源码路径分流;full.log 为汇总。@@ -941,12 +941,18 @@ modes:rails:tools:code:+ # 记忆开关 — 控制 CodingMemoryRail 和 ProjectMemoryRail 加载+ # 关闭后,coding_memory_read/write/edit 工具不可用,项目记忆文件不自动加载+ memory:+ enabled: true+# 动态 Rails — 列表中出现的 = 启用;不出现的 = 不启用# 固定 Rails(以下 Rails 已在代码中固定挂载,无需在此配置):# RuntimePromptRail, ResponsePromptRail, JiuSwarmStreamEventRail, SecurityRail,# PermissionInterruptRail, SysOperationRail(FileSystemRail), LspRail,- # ProjectMemoryRail, CodingMemoryRail, AgentModeRail, StructuredAskUserRail,- # ConfirmInterruptRail, ContextProcessorRail+ # AgentModeRail, StructuredAskUserRail, ConfirmInterruptRail, ContextProcessorRail+ # 注意:ProjectMemoryRail, CodingMemoryRail 受 memory.enabled 开关控制,+ # 开关关闭时不加载,开关开启时固定挂载。rails:- SkillUseRail- WorktreeRaildiff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 58283ffa20..9587621a29 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -18,10 +18,7 @@ import loggingimport reimport timefrom pathlib import Path-from typing import TYPE_CHECKING, Any, AsyncIterator, Tuple--if TYPE_CHECKING:- from openjiuwen.core.context_engine.engine import ContextEngine+from typing import Any, AsyncIterator, Tuplefrom datetime import datetime, timedelta, timezonefrom dotenv import load_dotenv@@ -31,7 +28,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+from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode, is_memory_enabledfrom jiuwenswarm.server.runtime.session.session_history import (append_compact_history_records,append_history_record,@@ -137,39 +134,51 @@ def _trigger_auto_memory_extraction(is_stream: Whether this is from stream mode (for logging)."""project_dir = request.params.get("project_dir") if isinstance(request.params, dict) else None- mode_label = "(stream)" if is_stream else ""- logger.info("[auto_memory] Trigger check %s: enabled=%s", mode_label, True)if not project_dir:- logger.info("[auto_memory] Skipped %s: no project_dir", mode_label)return- # Get context_engine from adapter._instance.react_agent- # adapter is AgentAdapter (e.g., CodeAgentRail), adapter._instance is DeepAgent- context_engine = None- adapter_instance = getattr(adapter, "_instance", None)- if adapter_instance is not None:- react_agent = getattr(adapter_instance, "react_agent", None)- if react_agent is not None:- context_engine = getattr(react_agent, "context_engine", None)- logger.debug("[auto_memory] context_engine obtained: %s",- type(context_engine).__name__ if context_engine else "None")- else:- logger.warning("[auto_memory] adapter._instance has no react_agent")- else:- logger.warning("[auto_memory] adapter has no _instance attribute")+ messages = None++ # Directly read messages from session history file+ try:+ from jiuwenswarm.server.runtime.session.session_history import read_session_history_records+ history_records = read_session_history_records(session_id)++ # Convert history records to message format for memory extraction+ # Each history record has: role, content, timestamp, etc.+ messages = []+ for record in history_records:+ role = record.get("role", "unknown")+ content = record.get("content", "")+ # Skip empty content+ if not content or not isinstance(content, str):+ continue+ # Create message dict in standard format+ messages.append({"role": role, "content": content})+ except Exception as e:+ logger.warning("[auto_memory] Failed to read session history: %s", e, exc_info=True)+ messages = None++ # If we successfully got messages, proceed with auto memory extraction+ if messages is None or len(messages) == 0:+ return- # Fire-and-forget: don't block on extraction- logger.info("[auto_memory] Launching extraction task %s", mode_label)- asyncio.create_task(- _execute_auto_memory_extraction(- project_dir=project_dir,- session_id=session_id,- request=request,- context_engine=context_engine,- parent_agent=adapter, # Pass adapter (not adapter._instance) for cache sharing+ # Launch auto memory extraction task+ try:+ asyncio.create_task(+ _execute_auto_memory_extraction(+ session_id=session_id,+ project_dir=project_dir,+ messages=messages,+ parent_agent=adapter, # Pass adapter for cache sharing+ ))- )+ mode = request.params.get("mode", "unknown") if isinstance(request.params, dict) else "unknown"+ logger.info("[auto_memory] Extraction task launched successfully for mode=%s", mode)+ except Exception as e:+ logger.error("[auto_memory] Failed to launch extraction task: %s", e, exc_info=True)+logger = logging.getLogger(__name__)@@ -1481,7 +1490,10 @@ class JiuWenSwarm:await ExtensionRegistry.get_instance().trigger(AgentServerHookEvents.MEMORY_AFTER_CHAT, after_ctx)# auto memory: extract memories after conversation ends- if is_auto_memory_enabled():+ # 需要 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):_trigger_auto_memory_extraction(adapter, request, session_id, is_stream=False)return result@@ -1915,7 +1927,10 @@ class JiuWenSwarm:await ExtensionRegistry.get_instance().trigger(AgentServerHookEvents.MEMORY_AFTER_CHAT, after_ctx)# auto memory: extract memories after conversation ends- if is_auto_memory_enabled():+ # 需要 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):_trigger_auto_memory_extraction(adapter, request, session_id, is_stream=True)yield AgentResponseChunk(diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex c7ee0f2f02..2a654640d5 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -61,7 +61,7 @@ from jiuwenswarm.agents.harness.common.rails import (ProjectMemoryRail,StructuredAskUserRail,)-from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode+from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode, is_memory_enabledfrom jiuwenswarm.agents.harness.common.tools import (SkillToolkit,)@@ -757,7 +757,13 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):"""构建 CodingMemoryRail(主 Agent 和 code_agent subagent 共用).通过 self._coding_memory_rail 缓存避免重复构建。+ 受 modes.code.memory.enabled 开关控制,关闭时返回 None。"""+ # 检查 memory 开关+ if not is_memory_enabled("code", get_config()):+ logger.info("[JiuwenSwarmCodeAdapter] CodingMemoryRail disabled by modes.code.memory.enabled")+ return None+# 单例保护:如果已构建,直接返回缓存实例if self._coding_memory_rail is not None:logger.info("[JiuwenSwarmCodeAdapter] CodingMemoryRail reuse cached instance")@@ -781,9 +787,14 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):def _build_project_memory_rail(self) -> ProjectMemoryRail | None:"""Build ProjectMemoryRail to auto-load JIUWENSWARM.md / CLAUDE.md etc.- Code 模式专属 — 始终挂载。+ Code 模式专属 — 受 modes.code.memory.enabled 开关控制。确保能检索到 /init 命令创建 JIUWENSWARM.md 的目录(当前工作目录)。"""+ # 检查 memory 开关+ if not is_memory_enabled("code", get_config()):+ logger.info("[JiuwenSwarmCodeAdapter] ProjectMemoryRail disabled by modes.code.memory.enabled")+ return None+try:workspace = self._project_dir or self._workspace_dir or "./"language = self._resolve_runtime_language()diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.pyindex 1c920ca62b..c7574fb743 100644--- a/jiuwenswarm/server/runtime/session/session_history.py+++ b/jiuwenswarm/server/runtime/session/session_history.py@@ -287,6 +287,31 @@ def read_team_history_records(session_id: str) -> list[dict[str, Any]]:return [item for item in all_records if isinstance(item, dict) and _is_team_relevant(item)]+def read_session_history_records(session_id: str) -> list[dict[str, Any]]:+ """读取指定会话的历史记录,返回所有记录。++ 用于 auto memory 功能提取对话消息。+ """+ fpath = _history_file(session_id)+ all_records = _read_history(fpath)+ # write_text 非原子写入(先截断再写入),读取可能命中截断窗口,+ # 用递增间隔重试最多 5 次等待写入完成+ if not all_records and fpath.exists():+ for attempt in range(1, 6):+ time.sleep(0.2 * attempt)+ all_records = _read_history(fpath)+ if all_records:+ logger.info("read_session_history_records: recovered on retry %d", attempt)+ break+ if not all_records:+ logger.warning(+ "read_session_history_records: all retries exhausted, file_size=%d",+ fpath.stat().st_size,+ )++ return [item for item in all_records if isinstance(item, dict)]++def _write_item(session_id: str, item: dict[str, Any]) -> None:with _FILE_LOCK:if use_legacy_history_json():diff --git a/tests/unit_tests/agentserver/memory/test_config_mode_resolution.py b/tests/unit_tests/agentserver/memory/test_config_mode_resolution.pyindex 32fc3eb6fa..214bc63960 100644--- a/tests/unit_tests/agentserver/memory/test_config_mode_resolution.py+++ b/tests/unit_tests/agentserver/memory/test_config_mode_resolution.py@@ -23,9 +23,13 @@ def _resolve_mode_memory(mode: str, config: Optional[Dict[str, Any]]) -> Dict[sttoken = (mode or "").strip()if "." in token:top, sub = token.split(".", 1)- node = modes_cfg.get(top, {})- if isinstance(node, dict):- node = node.get(sub, {})+ # Special handling for "code.*" -> modes.code (ignore sub_mode)+ if top == "code":+ node = modes_cfg.get("code", {})+ else:+ node = modes_cfg.get(top, {})+ if isinstance(node, dict):+ node = node.get(sub, {})elif token == "code":node = modes_cfg.get("code", {})else:@@ -87,6 +91,13 @@ def test_code_token_reads_modes_code(cfg):assert is_proactive_memory("code", cfg) is False[email protected]("token", ["code.normal", "code.team", "code.anything"])+def test_code_sub_tokens_route_to_modes_code(cfg, token):+ # "code.*" should resolve to modes.code, same as bare "code"+ assert is_memory_enabled(token, cfg) is False+ assert is_proactive_memory(token, cfg) is False++@pytest.mark.parametrize("token", ["weird", ""])def test_unknown_or_empty_token_returns_disabled(cfg, token):assert is_memory_enabled(token, cfg) is False