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(coding memory): auto memory
jingjinduodf871d97bc89
diff --git a/jiuwenswarm/agents/harness/common/auto_memory/__init__.py b/jiuwenswarm/agents/harness/common/auto_memory/__init__.pynew file mode 100644index 0000000000..4d2a01ad49--- /dev/null+++ b/jiuwenswarm/agents/harness/common/auto_memory/__init__.py@@ -0,0 +1,23 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Auto Memory module for jiuwenswarm.++This module implements automatic memory extraction after conversation ends,+similar to Claude Code's auto-memory feature.++Key components:+- extract_memories: Utility functions for scanning memory files, mutex detection, message conversion+- prompts: Prompt templates for memory extraction+- tool_restriction_rail: Rail for restricting tool calls (canUseTool-like)+- extraction_runner: Main extraction logic (subagent functions)+"""++from __future__ import annotations++from jiuwenswarm.agents.harness.common.auto_memory.extraction_runner import (+ _execute_auto_memory_extraction,+)++__all__ = [+ "_execute_auto_memory_extraction",+]\ 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.pynew file mode 100644index 0000000000..367d98ac4c--- /dev/null+++ b/jiuwenswarm/agents/harness/common/auto_memory/extract_memories.py@@ -0,0 +1,136 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Extract memories from conversation after it ends.++This module provides utility functions for memory extraction:+- scan_memory_files: Scan existing memory files in project memory directory+- _check_coding_memory_write_in_history: Mutex detection for coding_memory_write+- _convert_messages_to_base_messages: Message conversion helper++The main extraction logic is in extraction_runner.py.+"""++from __future__ import annotations++import logging+import re+from pathlib import Path+from typing import Any++logger = logging.getLogger(__name__)+++# Regex patterns for memory file frontmatter+_FRONTMATTER_PATTERN = re.compile(+ r"^---\s*\n"+ r"name:\s*(.+)\s*\n"+ r"description:\s*(.+)\s*\n"+ r"type:\s*(.+)\s*\n"+ r"---\s*\n",+ re.MULTILINE,+)+++def scan_memory_files(memory_dir: Path) -> list[dict[str, Any]]:+ """Scan existing memory files in the memory directory.++ Args:+ memory_dir: Path to the project memory directory.++ Returns:+ List of memory file metadata (name, description, type, path).+ """+ if not memory_dir.exists():+ return []++ memories: list[dict[str, Any]] = []++ for md_file in memory_dir.glob("*.md"):+ if md_file.name == "MEMORY.md":+ continue # Skip index file++ try:+ content = md_file.read_text(encoding="utf-8")+ match = _FRONTMATTER_PATTERN.match(content)+ if match:+ memories.append({+ "name": match.group(1).strip(),+ "description": match.group(2).strip(),+ "type": match.group(3).strip(),+ "path": str(md_file),+ "file_name": md_file.name,+ })+ except Exception as e:+ logger.warning(f"[auto_memory] Failed to read memory file {md_file}: {e}")++ return memories+++def _check_coding_memory_write_in_history(history_list: list) -> bool:+ """Check if coding_memory_write tool was actually called by assistant.++ Only checks tool_calls field, not message content, to avoid false positives+ when user mentions the tool name in their message.++ Args:+ history_list: List of message dicts with role/content/tool_calls fields.++ Returns:+ True if coding_memory_write was called, False otherwise.+ """+ for msg in history_list:+ # Only check assistant messages with actual tool_calls+ role = msg.get("role", "")+ if role != "assistant":+ continue+ tool_calls = msg.get("tool_calls", [])+ for tc in tool_calls:+ if isinstance(tc, dict):+ func_name = tc.get("function", {}).get("name", "")+ if func_name == "coding_memory_write":+ return True+ return False+++def _convert_messages_to_base_messages(messages: list[dict[str, Any] | Any]) -> list[Any]:+ """Convert dict messages to BaseMessage objects.++ Handles dict messages with role/content fields, BaseMessage-like objects,+ and unknown formats (converted to UserMessage with string content).++ Args:+ messages: List of messages (dict or BaseMessage-like objects).++ Returns:+ List of BaseMessage objects.+ """+ from openjiuwen.core.foundation.llm.schema.message import (+ UserMessage, AssistantMessage, SystemMessage, ToolMessage+ )++ converted = []+ for msg in messages:+ if isinstance(msg, dict):+ role = msg.get("role", "user")+ content = msg.get("content", "")+ if role == "user":+ converted.append(UserMessage(content=str(content)))+ elif role == "assistant":+ converted.append(AssistantMessage(content=str(content)))+ elif role == "system":+ converted.append(SystemMessage(content=str(content)))+ elif role == "tool":+ converted.append(ToolMessage(content=str(content)))+ else:+ # Fallback to user message+ converted.append(UserMessage(content=str(content)))+ elif hasattr(msg, "role") and hasattr(msg, "content"):+ # Already a BaseMessage-like object+ converted.append(msg)+ else:+ # Unknown format, convert to string+ converted.append(UserMessage(content=str(msg)))++ return converted++diff --git a/jiuwenswarm/agents/harness/common/auto_memory/extraction_runner.py b/jiuwenswarm/agents/harness/common/auto_memory/extraction_runner.pynew file mode 100644index 0000000000..3bd10f67ae--- /dev/null+++ b/jiuwenswarm/agents/harness/common/auto_memory/extraction_runner.py@@ -0,0 +1,499 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Auto Memory Extraction Runner - Memory extraction subagent functions.++This module provides functions for extracting memories from conversations:+- _MemoryExtractionContext: Context dataclass for extraction resources+- _create_memory_extraction_context: Workspace/SysOperation/ToolContext creation+- _execute_auto_memory_extraction: Main entry point for extraction+- _run_simple_memory_extraction: Standalone subagent extraction+- _run_memory_extraction_with_cache_sharing: Cache-sharing extraction mode+"""++from __future__ import annotations++import asyncio+import logging+import time+from dataclasses import dataclass+from pathlib import Path+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from openjiuwen.core.context_engine.engine import ContextEngine+ from jiuwenswarm.server.runtime.agent_adapter.agent_adapters import AgentAdapter+ from jiuwenswarm.common.schema.agent import AgentRequest++logger = logging.getLogger(__name__)+++@dataclass+class _MemoryExtractionContext:+ """Context object for memory extraction subagents.++ Contains all shared resources needed for memory extraction:+ - Workspace for file operations+ - SysOperation for sandbox restrictions+ - CodingMemoryToolContext for memory tools+ - Memory tools for write/edit/read operations+ """++ workspace: Any # Workspace+ sys_operation: Any # SysOperation+ sysop_id: str+ tool_ctx: Any # CodingMemoryToolContext+ memory_tools: list[Any]++ def cleanup(self) -> None:+ """Remove SysOperation to free resources."""+ from openjiuwen.core.runner.runner import Runner+ try:+ Runner.resource_mgr.remove_sys_operation(self.sysop_id)+ except Exception as cleanup_err:+ logger.warning("[auto_memory] Cleanup failed: %s", cleanup_err)+++async def _create_memory_extraction_context(+ memory_dir: Path,+ agent_id: str = "auto_memory_subagent",+ sysop_id_prefix: str = "extract_memories_",+) -> _MemoryExtractionContext | None:+ """Create shared context for memory extraction subagents.++ This function creates all shared resources needed for memory extraction:+ - Workspace pointing to memory_dir+ - SysOperation restricted to memory_dir+ - CodingMemoryToolContext for vector-indexed memory tools+ - Coding memory tools (write/edit/read)++ Args:+ memory_dir: Path to the coding memory directory.+ agent_id: Agent ID for the tool context.+ sysop_id_prefix: Prefix for SysOperation ID (default: "extract_memories_").++ Returns:+ _MemoryExtractionContext if successful, None if SysOperation creation fails.+ """+ from openjiuwen.core.runner.runner import Runner+ from openjiuwen.core.sys_operation import SysOperation, SysOperationCard, OperationMode+ from openjiuwen.core.sys_operation.config import LocalWorkConfig+ from openjiuwen.harness.workspace.workspace import Workspace+ from openjiuwen.core.memory.lite.coding_memory_tool_context import CodingMemoryToolContext+ from openjiuwen.core.memory.lite.config import create_memory_settings+ from openjiuwen.harness.tools.coding_memory import create_coding_memory_tools++ # Ensure memory directory exists+ memory_dir.mkdir(parents=True, exist_ok=True)++ # Create Workspace+ workspace = Workspace(root_path=str(memory_dir), language="cn")+ workspace.set_directory({+ "name": "coding_memory",+ "path": ".", # Points to root_path (memory_dir), not a subdirectory+ "type": "directory",+ })++ # Create SysOperation restricted to memory directory+ sysop_id = f"{sysop_id_prefix}{int(time.time())}"+ sysop_card = SysOperationCard(+ id=sysop_id,+ mode=OperationMode.LOCAL,+ work_config=LocalWorkConfig(+ sandbox_root=[str(memory_dir)],+ restrict_to_sandbox=True,+ ),+ )++ # Register SysOperation+ add_result = Runner.resource_mgr.add_sys_operation(sysop_card)+ if add_result.is_err():+ logger.error("[auto_memory] Failed to add SysOperation: %s", add_result.msg())+ return None++ sys_operation = Runner.resource_mgr.get_sys_operation(sysop_id)+ if sys_operation is None:+ logger.error("[auto_memory] Failed to get SysOperation")+ return None++ # Create CodingMemoryToolContext+ settings = create_memory_settings(str(memory_dir))+ tool_ctx = CodingMemoryToolContext(+ workspace=workspace,+ settings=settings,+ agent_id=agent_id,+ embedding_config=None,+ sys_operation=sys_operation,+ coding_memory_dir=str(memory_dir),+ manager=None,+ node_name="", # Empty to write directly to memory_dir, not nested subdir+ )++ # Create coding memory tools+ memory_tools = create_coding_memory_tools(tool_ctx, language="cn")+ tool_ctx.coding_memory_dir = str(memory_dir)++ # Create .workspace marker file+ workspace_marker = memory_dir / ".workspace"+ if not workspace_marker.exists():+ workspace_marker.write_text("", encoding="utf-8")++ return _MemoryExtractionContext(+ workspace=workspace,+ sys_operation=sys_operation,+ sysop_id=sysop_id,+ tool_ctx=tool_ctx,+ memory_tools=memory_tools,+ )+++async def _execute_auto_memory_extraction(+ project_dir: str,+ session_id: str,+ request: "AgentRequest",+ context_engine: "ContextEngine | None" = None,+ parent_agent: "AgentAdapter | None" = None,+) -> None:+ """Execute auto memory extraction in background.++ This is a fire-and-forget helper that wraps execute_extract_memories.++ 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.+ parent_agent: The parent AgentAdapter instance (for cache sharing, optional).+ """+ # Import utility functions from extract_memories module+ from jiuwenswarm.agents.harness.common.auto_memory.extract_memories import (+ _check_coding_memory_write_in_history,+ scan_memory_files,+ )++ try:+ logger.debug("[auto_memory] Extraction task started")++ # Validate project_dir: must be an existing directory+ if not project_dir:+ logger.warning("[auto_memory] Skipped: project_dir is empty")+ return++ project_path = Path(project_dir)+ if not project_path.exists():+ logger.warning("[auto_memory] Skipped: project_dir does not exist")+ return++ if not project_path.is_dir():+ logger.warning("[auto_memory] Skipped: project_dir is not a directory")+ return++ # Get conversation messages from context engine+ history = []+ if context_engine is None:+ logger.warning("[auto_memory] context_engine is None, cannot retrieve messages")+ else:+ 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)++ if not history:+ logger.debug("[auto_memory] Skipped: no conversation messages found")+ return++ # Mutex detection: check if main agent used coding_memory_write+ # If so, skip auto memory subagent (main agent already handled memory)+ if _check_coding_memory_write_in_history(history):+ logger.info(+ "[auto_memory] Skipped: main agent used coding_memory_write (mutex detection)"+ )+ return++ # Count new messages (this turn's exchange)+ # Typically 1 user message + 1 assistant message per turn+ new_messages_count = 2 # Simplified count++ # Get coding memory directory (unified with Auto Memory)+ from jiuwenswarm.common.utils import get_agent_workspace_dir+ from jiuwenswarm.common.coding_memory_paths import resolve_project_coding_memory_dir+ memory_dir = Path(resolve_project_coding_memory_dir(+ agent_workspace_dir=get_agent_workspace_dir(),+ project_dir=project_dir,+ ))++ # Ensure memory directory exists+ memory_dir.mkdir(parents=True, exist_ok=True)+ memory_md = memory_dir / "MEMORY.md"+ if not memory_md.exists():+ memory_md.write_text(+ "# Project Auto Memory Index\n\n"+ "# This file is automatically updated by extractMemories.\n"+ "# Each entry links to a memory file.\n\n",+ encoding="utf-8",+ )++ # Scan existing memories+ existing_memories = scan_memory_files(memory_dir)+ logger.debug("[auto_memory] Existing memories: %d files", len(existing_memories))++ # Build extraction prompt+ from jiuwenswarm.agents.harness.common.auto_memory.prompts import build_extract_memories_prompt+ prompt = build_extract_memories_prompt(+ new_messages_count=new_messages_count,+ existing_memories=existing_memories,+ language="zh",+ )++ # 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,+ history=history,+ existing_memories=existing_memories,+ parent_agent=parent_agent,+ )++ logger.debug("[auto_memory] Extraction task completed")++ except Exception as e:+ logger.error("[auto_memory] Extraction failed: %s", e, exc_info=True)+++async def _run_memory_extraction_with_cache_sharing(+ memory_dir: Path,+ prompt: str,+ history: list[dict[str, Any]],+ existing_memories: list[dict[str, Any]],+ parent_agent: "AgentAdapter",+) -> None:+ """Run memory extraction with API cache sharing.++ Similar to Claude Code's ForkedAgent pattern:+ - Inherits parent agent's model, system_prompt, and tools+ - Inherits parent agent's message prefix (via create_new_context_engine)+ - Runtime tool restriction via AutoMemoryToolRestrictionRail++ This enables API cache hit because all cache key components match:+ - system_prompt (inherited)+ - tools (inherited, runtime restriction doesn't change tool definitions)+ - model (inherited)+ - messages prefix (inherited)++ Args:+ memory_dir: Path to the coding memory directory.+ prompt: The extraction prompt.+ history: The conversation history.+ existing_memories: List of existing memory files.+ parent_agent: The parent DeepAgent instance to inherit from.+ """+ # Import utility functions from extract_memories module+ from jiuwenswarm.agents.harness.common.auto_memory.extract_memories import (+ _convert_messages_to_base_messages,+ )++ try:+ from jiuwenswarm.agents.harness.common.auto_memory.tool_restriction_rail import (+ AutoMemoryToolRestrictionRail,+ )+ from openjiuwen.core.single_agent.schema.agent_card import AgentCard+ from openjiuwen.harness.factory import create_deep_agent+ from openjiuwen.core.session.agent import Session++ logger.debug("[auto_memory] Cache sharing mode start")++ # Get parent agent's DeepAgent instance (adapter._instance)+ parent_instance = getattr(parent_agent, "_instance", None)+ if parent_instance is None:+ logger.error("[auto_memory] Parent adapter has no _instance, cannot proceed")+ return++ # 1. Get parent agent's model+ parent_model = getattr(parent_instance, "deep_config", None)+ if parent_model is not None:+ parent_model = getattr(parent_model, "model", None)++ if parent_model is None:+ logger.error("[auto_memory] Parent agent has no model, cannot proceed")+ return++ # 2. Get parent agent's actual tools sent to LLM+ # IMPORTANT: ability_manager.list() returns all registered tools+ # These are the actual tools sent to the LLM (after duplicate filtering in DeepAgent)+ parent_tools = []+ if hasattr(parent_instance, "ability_manager"):+ parent_tools = list(parent_instance.ability_manager.list() or [])++ # 2.5. Get parent agent's system_prompt for cache key matching+ parent_system_prompt = None+ if hasattr(parent_instance, "deep_config") and parent_instance.deep_config is not None:+ parent_system_prompt = getattr(parent_instance.deep_config, "system_prompt", None)+ if parent_system_prompt is None:+ # Fallback: try to get from system_prompt_builder+ if hasattr(parent_instance, "system_prompt_builder") and parent_instance.system_prompt_builder is not None:+ # Build prompt dynamically - but this may differ from actual cached prompt+ logger.warning(+ "[auto_memory] Parent system_prompt is None, will use extraction prompt (may affect cache)"+ )+ # 2.6. Create context_engine_config with no limit for sub-agent+ # auto-memory needs full history, so set max_context_message_num=None (unlimited)+ from openjiuwen.core.context_engine import ContextEngineConfig+ subagent_context_config = ContextEngineConfig(+ max_context_message_num=None, # No message limit+ default_window_round_num=None, # No round limit+ )+ # 3. Get parent agent's rails for system prompt consistency+ # Inherit RuntimePromptRail and ProjectMemoryRail to ensure dynamic content injection+ # Rails are stored directly on the adapter (not on _instance)+ parent_rails = []+ # RuntimePromptRail (always present in code mode)+ _runtime_rail = getattr(parent_agent, "_runtime_prompt_rail", None)+ if _runtime_rail is not None:+ parent_rails.append(_runtime_rail)+ # ProjectMemoryRail (code mode only)+ _project_rail = getattr(parent_agent, "_project_memory_rail", None)+ if _project_rail is not None:+ parent_rails.append(_project_rail)+ # CodingMemoryRail (code mode only)+ _coding_rail = getattr(parent_agent, "_coding_memory_rail", None)+ if _coding_rail is not None:+ parent_rails.append(_coding_rail)++ # 4. Create AutoMemoryToolRestrictionRail for runtime tool restriction+ restriction_rail = AutoMemoryToolRestrictionRail(memory_dir=str(memory_dir))++ # 5. Create shared extraction context (Workspace, SysOperation, ToolContext, MemoryTools)+ ctx = await _create_memory_extraction_context(+ memory_dir,+ agent_id="auto_memory_cache_subagent",+ sysop_id_prefix="extract_memories_cache_",+ )+ if ctx is None:+ logger.error("[auto_memory] Failed to create extraction context")+ return++ # 6. Combine parent tools with memory tools+ # Note: For cache sharing, parent_tools should match parent's tool definitions+ # memory_tools are added for memory writing capability+ combined_tools = list(parent_tools) + list(ctx.memory_tools)++ # 7. Create agent card for extract memories subagent+ agent_card = AgentCard(+ name="extractMemoriesCache",+ description="Extract memories with cache sharing",+ )++ # 8. Build extraction prompt (will be sent as user message for cache key matching)+ # IMPORTANT: For cache sharing, we must use parent's system_prompt+ # and send extraction instructions via user message+ extraction_query = f"{prompt}\n\n请分析对话内容并提取记忆,使用 coding_memory_write 工具更新记忆文件。"++ # Use parent's system_prompt if available (for cache key matching)+ # Otherwise fallback to extraction prompt+ subagent_system_prompt = parent_system_prompt if parent_system_prompt else extraction_query++ # 9. Create subagent with parent's model, tools, and rails for cache sharing+ subagent_rails = parent_rails + [restriction_rail]++ sub_agent = create_deep_agent(+ model=parent_model, # Inherit parent's model for cache sharing+ card=agent_card,+ system_prompt=subagent_system_prompt, # Inherit parent's system_prompt for cache+ tools=combined_tools, # Combined tools (parent + memory)+ workspace=ctx.workspace,+ sys_operation=ctx.sys_operation,+ restrict_to_work_dir=True,+ enable_task_loop=False,+ max_iterations=10, # Keep loose upper limit, actual rounds should be low+ rails=subagent_rails, # Inherit parent's rails + restriction_rail+ context_engine_config=subagent_context_config, # No limit for full history+ )++ logger.debug("[auto_memory] Subagent created (cache sharing mode)")++ # 10. Create new context engine inheriting parent's message prefix+ # forkContextMessages pattern: pass full history for cache sharing (like Claude Code)+ fork_prefix_messages_raw = history++ # Convert dict messages to BaseMessage objects+ fork_prefix_messages = _convert_messages_to_base_messages(fork_prefix_messages_raw)++ try:+ # IMPORTANT: Must use sub_agent's context_engine, not parent_agent's!+ # sub_agent has its own independent context_engine._context_pool+ # Creating context on parent_agent won't transfer to sub_agent+ new_session_id = await sub_agent.create_new_context_engine(+ messages=fork_prefix_messages,+ )+ except Exception as ctx_err:+ logger.error("[auto_memory] Failed to create context engine: %s", ctx_err)+ return++ # 11. Invoke subagent with inherited session+ new_session = Session(session_id=new_session_id, card=sub_agent.card)++ # Send extraction instructions via user message+ extraction_input = extraction_query if parent_system_prompt else "请提取记忆"++ logger.debug("[auto_memory] === INVOKING SUBAGENT ===")+ try:+ invoke_start_time = asyncio.get_event_loop().time()++ # Use stream mode to match parent agent's streaming mode for cache sharing+ # IMPORTANT: Parent agent uses stream mode, so subagent must also use stream+ # to match cache key (is_stream parameter affects cache key)+ result_chunks = []+ async for chunk in sub_agent.stream(+ {"query": extraction_input},+ session=new_session,+ ):+ result_chunks.append(chunk)++ # Collect final result from stream+ # The last chunk or accumulated chunks should contain the final result+ result = result_chunks[-1] if result_chunks else None++ # Add timestamp after invoke+ invoke_end_time = asyncio.get_event_loop().time()+ invoke_duration = invoke_end_time - invoke_start_time+ logger.debug("[auto_memory] === SUBAGENT INVOKE COMPLETED === (duration: %.2fs)", invoke_duration)+ except Exception as invoke_err:+ logger.error("[auto_memory] === SUBAGENT INVOKE FAILED ===")+ logger.error("[auto_memory] Invoke error: %s", invoke_err, exc_info=True)+ raise++ # 12. Check result+ if result is None:+ logger.warning("[auto_memory] Subagent returned no result")++ # 13. Check created files+ created_files = list(memory_dir.glob("*.md"))+ logger.info("[auto_memory] Memory files: %d - %s",+ len(created_files), [f.name for f in created_files])++ # 14. Cleanup+ ctx.cleanup()++ logger.info("[auto_memory] === CACHE SHARING MODE END ===")++ except Exception as e:+ logger.error("[auto_memory] Cache sharing extraction failed: %s", e, exc_info=True)++diff --git a/jiuwenswarm/agents/harness/common/auto_memory/prompts.py b/jiuwenswarm/agents/harness/common/auto_memory/prompts.pynew file mode 100644index 0000000000..1a2e9090ee--- /dev/null+++ b/jiuwenswarm/agents/harness/common/auto_memory/prompts.py@@ -0,0 +1,197 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Prompt templates for Auto Memory extraction.++Based on Claude Code's extractMemories prompts design.+"""++from __future__ import annotations++from typing import Any+++def build_extract_memories_prompt(+ new_messages_count: int,+ existing_memories: list[dict[str, Any]],+ language: str = "zh",+) -> str:+ """Build the prompt for memory extraction.++ Args:+ new_messages_count: Number of new messages in this conversation.+ existing_memories: List of existing memory files (from scan_memory_files).+ language: Language for the prompt (zh or en).++ Returns:+ The prompt string.+ """+ if language == "zh":+ return _build_extract_prompt_zh(new_messages_count, existing_memories)+ return _build_extract_prompt_en(new_messages_count, existing_memories)+++def _build_extract_prompt_zh(+ new_messages_count: int,+ existing_memories: list[dict[str, Any]],+) -> str:+ """Build Chinese prompt for memory extraction."""+ existing_summary = ""+ if existing_memories:+ existing_summary = "\n现有记忆文件:\n"+ for mem in existing_memories:+ existing_summary += f"- {mem.get('name', 'unknown')}: {mem.get('description', '')}\n"++ return f"""你是一个记忆提取助手。请从对话中提取值得记忆的信息。++## 任务说明++这是一个**系统自动任务**,在对话结束后自动触发。你的职责是自动提取和记录用户偏好、反馈等信息。++对话中有 {new_messages_count} 条新消息。请分析这些消息,提取以下类型的记忆:++1. **user** - 用户画像(角色、偏好、知识)+2. **feedback** - 用户反馈(避免什么、保持什么)+3. **project** - 项目信息(目标、进度、决策)+4. **reference** - 外部资源指针(URLs、dashboards、tickets)++## 重要说明:关于用户意图的理解++⚠️ **特别注意**:+- 如果用户说"让 auto-memory 处理"、"让系统自动处理"或类似表述,这正是**触发你执行此任务的原因**,意味着用户希望你来提取和记录这些信息。+- 不要误解用户的意图。"不要主动记录"是指主 agent 不要在对话中主动记录,而你作为记忆提取子 agent,执行此任务就是用户期望的"auto-memory 处理"。+- 你的任务就是 auto-memory 系统的核心功能,请认真分析对话并提取值得记忆的信息。++## 不要记忆的内容++- 可从代码/git 历史推导的内容+- 临时性信息+- 频繁变化的信息+- 密码、API密钥等敏感信息++{existing_summary}++## 输出要求++**⚠️ 重要:执行效率优化**++你的执行轮次有限(最多 5 轮),请采用高效策略:+- **第 1 轮**:并行读取所有可能需要查看的文件(MEMORY.md、现有记忆文件等)+- **第 2 轮**:并行执行所有写入操作(coding_memory_write 创建新文件、coding_memory_edit 更新现有文件)+- **避免交错读写**:不要在一轮中既读又写,这样会浪费轮次++示例高效流程:+```+Round 1: coding_memory_read(MEMORY.md), coding_memory_read(现有记忆文件)+Round 2: coding_memory_write(新记忆), coding_memory_edit(MEMORY.md 更新索引)+完成!+```++具体操作:++1. 如果发现新的值得记忆的信息:+ - 使用 coding_memory_write 工具创建记忆文件+ - 文件路径:{{语义命名}}.md(如 user_preferences.md)+ - 格式:YAML frontmatter + Markdown 内容+ - 然后使用 coding_memory_edit 工具更新 MEMORY.md 索引++2. 如果现有记忆需要更新:+ - 使用 coding_memory_edit 工具更新对应的记忆文件+ - 如果需要,更新 MEMORY.md 索引++3. 如果没有值得记忆的内容:+ - 不做任何操作++## 记忆文件格式示例++```markdown+---+name: user-preferences+description: User's coding and communication preferences+type: user+---++## 代码风格偏好+- 偏好简洁的代码风格+- 不喜欢过度封装++## 沟通偏好+- 习惯用中文交流+```++## MEMORY.md 索引格式示例++```markdown+- [user] user_preferences.md (2026-06-10T10:30:00): 简洁代码风格,中文交流+```++请开始分析对话内容并提取记忆。"""+++def _build_extract_prompt_en(+ new_messages_count: int,+ existing_memories: list[dict[str, Any]],+) -> str:+ """Build English prompt for memory extraction."""+ existing_summary = ""+ if existing_memories:+ existing_summary = "\nExisting memory files:\n"+ for mem in existing_memories:+ existing_summary += f"- {mem.get('name', 'unknown')}: {mem.get('description', '')}\n"++ return f"""You are a memory extraction assistant. Extract memorable information from the conversation.++## Task Description++There are {new_messages_count} new messages in this conversation. Analyze them and extract memories of these types:++1. **user** - User profile (role, preferences, knowledge)+2. **feedback** - User feedback (what to avoid, what to keep)+3. **project** - Project information (goals, progress, decisions)+4. **reference** - External resource pointers (URLs, dashboards, tickets)++## What NOT to remember++- Content derivable from code/git history+- Temporary information+- Frequently changing information+- Passwords, API keys, and other sensitive information++{existing_summary}++## Output Requirements++1. If you find new memorable information:+ - Use coding_memory_write tool to create memory file+ - File path: {semantic-name}.md (e.g., user_role.md)+ - Format: YAML frontmatter + Markdown content+ - Then use coding_memory_edit tool to update MEMORY.md index++2. If existing memories need updates:+ - Use coding_memory_edit tool to update the corresponding memory file+ - Update MEMORY.md index if needed++3. If nothing worth remembering:+ - Do nothing++## Memory File Format Example++```markdown+---+name: user-role+description: User's role and focus+type: user+---++User is a data scientist focused on observability/logging domain.+Prefers log analysis over breakpoint debugging when troubleshooting.+```++## MEMORY.md Index Format Example++```markdown+- [user] user_role.md (2026-06-09T10:30:00): Data scientist focused on observability+```++Please analyze the conversation and extract memories. """++diff --git a/jiuwenswarm/agents/harness/common/auto_memory/tool_restriction_rail.py b/jiuwenswarm/agents/harness/common/auto_memory/tool_restriction_rail.pynew file mode 100644index 0000000000..34dc26eb38--- /dev/null+++ b/jiuwenswarm/agents/harness/common/auto_memory/tool_restriction_rail.py@@ -0,0 +1,353 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""AutoMemoryToolRestrictionRail - restrict tool calls for extract_memories subagent.++Similar to Claude Code's canUseTool mechanism:+- Allows Read/Grep/Glob tools (unrestricted)+- Allows Bash read-only commands (ls, cat, git status, etc.)+- Allows Write/Edit only in memory_dir+- Denies other tools by setting ctx.extra["_skip_tool"] = True++This enables cache sharing: the subagent inherits parent's tools,+but runtime restriction prevents unauthorized tool use.+"""++from __future__ import annotations++import logging+from pathlib import Path+from typing import Any, Dict++from openjiuwen.core.single_agent.rail.base import AgentRail, AgentCallbackContext++logger = logging.getLogger(__name__)+++# Tool names that are allowed without restrictions+UNRESTRICTED_READ_TOOLS = (+ "read_file",+ "read",+ "grep",+ "glob",+ "list_files",+ "search",+)++# Bash commands that are read-only (allowed)+READ_ONLY_BASH_COMMANDS = (+ "ls",+ "cat",+ "head",+ "tail",+ "grep",+ "find",+ "git status",+ "git log",+ "git diff",+ "git show",+ "pwd",+ "echo",+ "wc",+ "stat",+ "file",+)+++class AutoMemoryToolRestrictionRail(AgentRail):+ """Restrict tool calls for extract_memories subagent.++ This Rail implements the canUseTool-like mechanism for jiuwenswarm:+ - Checks tool_name and tool_args before each tool execution+ - Sets ctx.extra["_skip_tool"] = True to deny unauthorized tool calls+ - Sets ctx.inputs.tool_result with denial message++ This enables API cache sharing because:+ - The subagent inherits parent's system_prompt and tools+ - Tools are restricted at runtime, not by creating different tool definitions+ - All cache key components (system_prompt, tools, model, messages prefix) match++ Usage:+ restriction_rail = AutoMemoryToolRestrictionRail(memory_dir="/path/to/memory")+ sub_agent = create_deep_agent(+ ...,+ rails=[restriction_rail],+ )++ Attributes:+ memory_dir: Path to the memory directory (allowed write location)+ priority: Rail execution priority (higher runs first)+ """++ priority: int = 100 # High priority to run before other rails++ def __init__(self, memory_dir: str):+ """Initialize the tool restriction rail.++ Args:+ memory_dir: Path to the memory directory where Write/Edit are allowed.+ """+ self.memory_dir = Path(memory_dir).resolve()+ logger.debug(+ "[auto_memory] AutoMemoryToolRestrictionRail initialized with memory_dir: %s",+ self.memory_dir,+ )++ async def before_tool_call(self, ctx: AgentCallbackContext) -> None:+ """Check tool permission before execution.++ This is the core canUseTool-like check:+ 1. Get tool_name and tool_args from ctx.inputs+ 2. Check against allowed patterns+ 3. Set ctx.extra["_skip_tool"] = True if denied++ Args:+ ctx: AgentCallbackContext containing tool call information.+ """+ # Get tool call info from ctx.inputs+ tool_inputs = ctx.inputs+ if not isinstance(tool_inputs, dict):+ # Should be ToolCallInputs, but access as dict-like+ tool_name = getattr(tool_inputs, "tool_name", "")+ tool_args = getattr(tool_inputs, "tool_args", {}) or {}+ else:+ tool_name = tool_inputs.get("tool_name", "")+ tool_args = tool_inputs.get("tool_args", {}) or {}++ # Ensure tool_args is a dict (sometimes it's a JSON string from LLM output)+ if not isinstance(tool_args, dict):+ if isinstance(tool_args, str):+ # Try to parse JSON string to dict+ try:+ import json+ tool_args = json.loads(tool_args)+ logger.debug(+ "[auto_memory] Successfully parsed tool_args JSON string for tool '%s'",+ tool_name,+ )+ except json.JSONDecodeError as e:+ logger.warning(+ f"[auto_memory] Failed to parse tool_args JSON string for tool '{tool_name}': {e}"+ )+ tool_args = {}+ else:+ logger.warning(+ f"[auto_memory] tool_args is not dict or string (type={type(tool_args).__name__}), "+ f"converting to empty dict for tool '{tool_name}'"+ )+ tool_args = {}++ # Log the check+ logger.debug(+ "[auto_memory] AutoMemoryToolRestrictionRail checking tool: %s",+ tool_name,+ )++ # 1. Check unrestricted read tools+ if self._is_unrestricted_read_tool(tool_name):+ logger.debug("[auto_memory] Tool '%s' allowed (unrestricted read)", tool_name)+ return # Allow execution++ # 2. Check Bash read-only commands+ if tool_name in ("bash", "execute_bash", "run_command", "shell"):+ if self._is_read_only_bash_command(tool_args):+ logger.debug(+ "[auto_memory] Bash command allowed (read-only): %s",+ tool_args.get("command", "")[:50],+ )+ return # Allow read-only bash++ # 3. Check Write/Edit in memory_dir+ if tool_name in ("write_file", "write", "edit_file", "edit"):+ if self._is_in_memory_dir(tool_args):+ logger.debug(+ "[auto_memory] Write/Edit allowed in memory_dir: %s",+ tool_args.get("file_path", ""),+ )+ return # Allow write in memory_dir++ # 4. Check coding_memory_write/edit (allowed for vector indexing)+ if tool_name in ("coding_memory_write", "coding_memory_edit"):+ if self._is_in_memory_dir(tool_args):+ logger.debug(+ "[auto_memory] coding_memory tool allowed: %s",+ tool_name,+ )+ return # Allow coding memory tools in memory_dir++ # 4.5. Check coding_memory_read (always allowed - read-only operation)+ if tool_name in ("coding_memory_read", "ltm_search", "ltm_search_summary"):+ logger.debug(+ "[auto_memory] Read-only memory tool allowed: %s",+ tool_name,+ )+ return # Allow read-only memory tools++ # 5. Deny all other tools+ logger.warning(+ f"[auto_memory] Tool '{tool_name}' DENIED by AutoMemoryToolRestrictionRail"+ )+ self._deny_tool(ctx, tool_name, tool_args)++ def _is_unrestricted_read_tool(self, tool_name: str) -> bool:+ """Check if tool is an unrestricted read tool.++ Args:+ tool_name: Name of the tool.++ Returns:+ True if the tool is allowed without restrictions.+ """+ return tool_name.lower() in (t.lower() for t in UNRESTRICTED_READ_TOOLS)++ def _is_read_only_bash_command(self, tool_args: Dict[str, Any]) -> bool:+ """Check if bash command is read-only.++ Args:+ tool_args: Tool arguments containing 'command' field.++ Returns:+ True if the command is read-only (no file modification).+ """+ command = tool_args.get("command", "")+ if not command:+ return False++ # Check against read-only command patterns+ command_lower = command.lower()+ for allowed_cmd in READ_ONLY_BASH_COMMANDS:+ if allowed_cmd.lower() in command_lower:+ return True++ # Also check for explicit read-only flags+ # e.g., "git status --porcelain" is safe+ if any(+ flag in command_lower+ for flag in ("--status", "--list", "--show", "--print", "--read")+ ):+ return True++ return False++ def _is_in_memory_dir(self, tool_args: Dict[str, Any]) -> bool:+ """Check if the target path is within memory_dir.++ Args:+ tool_args: Tool arguments containing 'file_path' or 'path' field.++ Returns:+ True if the path is within memory_dir.+ """+ # Get the file path from tool_args+ path = tool_args.get("file_path", "")+ if not path:+ # Also check 'path' field (coding_memory_write uses this)+ path = tool_args.get("path", "")++ if not path:+ return False++ try:+ # Handle relative paths (coding_memory_write uses relative paths)+ if Path(path).is_absolute():+ target_path = Path(path).resolve()+ else:+ # Relative path: resolve relative to memory_dir+ target_path = (self.memory_dir / path).resolve()++ # Check if target is within memory_dir+ # Use relative_to() for more robust check+ try:+ target_path.relative_to(self.memory_dir)+ logger.debug(+ "[auto_memory] Path '%s' resolved to '%s' is within memory_dir",+ path, target_path,+ )+ return True+ except ValueError:+ # relative_to() raises ValueError if not a subpath+ logger.debug(+ "[auto_memory] Path '%s' resolved to '%s' is NOT within memory_dir",+ path, target_path,+ )+ return False+ except Exception as e:+ logger.warning(+ f"[auto_memory] Failed to resolve path '{path}': {e}"+ )+ return False++ def _deny_tool(+ self,+ ctx: AgentCallbackContext,+ tool_name: str,+ tool_args: Dict[str, Any],+ ) -> None:+ """Deny the tool execution by setting _skip_tool.++ This is the key mechanism for runtime tool restriction:+ - Set ctx.extra["_skip_tool"] = True to skip execution+ - Set ctx.inputs.tool_result with denial message+ - Set ctx.inputs.tool_msg with tool denial message++ Args:+ ctx: AgentCallbackContext to modify.+ tool_name: Name of the denied tool.+ tool_args: Arguments of the denied tool.+ """+ # Set the skip flag+ ctx.extra["_skip_tool"] = True++ # Build the denial message+ denial_msg = (+ f"Tool '{tool_name}' is not allowed in extract_memories subagent.\n"+ f"Allowed tools: Read/Grep/Glob (unrestricted), Bash (read-only), "+ f"Write/Edit (only in memory_dir: {self.memory_dir}).\n"+ f"Your call with args {tool_args} was denied."+ )++ # Set the tool_result (for the return value)+ # Handle both ToolCallInputs dataclass and dict inputs+ if hasattr(ctx.inputs, "tool_result"):+ ctx.inputs.tool_result = {+ "success": False,+ "error": denial_msg,+ }+ elif isinstance(ctx.inputs, dict):+ ctx.inputs["tool_result"] = {+ "success": False,+ "error": denial_msg,+ }++ # Set the tool_msg (for the LLM to see)+ # Get tool_call_id from ctx.inputs.tool_call+ tool_call_id = ""+ if hasattr(ctx.inputs, "tool_call"):+ tool_call_obj = ctx.inputs.tool_call+ if hasattr(tool_call_obj, "id"):+ tool_call_id = tool_call_obj.id or ""+ elif isinstance(tool_call_obj, dict):+ tool_call_id = tool_call_obj.get("id", "")++ if hasattr(ctx.inputs, "tool_msg"):+ # Import ToolMessage if available+ try:+ from openjiuwen.core.foundation.llm.schema.message import ToolMessage+ ctx.inputs.tool_msg = ToolMessage(+ content=denial_msg,+ tool_call_id=tool_call_id,+ )+ except ImportError:+ # Fallback: use dict-like structure+ ctx.inputs.tool_msg = {+ "role": "tool",+ "content": denial_msg,+ "tool_call_id": tool_call_id,+ }+ elif isinstance(ctx.inputs, dict):+ ctx.inputs["tool_msg"] = {+ "role": "tool",+ "content": denial_msg,+ "tool_call_id": tool_call_id,+ }++diff --git a/jiuwenswarm/agents/harness/common/memory_rpc.py b/jiuwenswarm/agents/harness/common/memory_rpc.pyindex 360e661b75..8c438ebb8c 100644--- a/jiuwenswarm/agents/harness/common/memory_rpc.py+++ b/jiuwenswarm/agents/harness/common/memory_rpc.py@@ -230,12 +230,8 @@ async def handle_memory_list(})seen_paths.add(f.path)- memory_dir = os.path.join(workspace, "memory")- for item in _scan_md_files(memory_dir, "auto", workspace, project_dir):- if item["path"] not in seen_paths:- files.append(item)- seen_paths.add(item["path"])-+ # Auto-memory: unified with coding memory directory+ # Scan coding memory directory (auto-memory files are also stored there)coding_dir = _get_coding_memory_dir(workspace, project_dir)for item in _scan_md_files(coding_dir, "coding", workspace, project_dir):if item["path"] not in seen_paths:@@ -294,6 +290,8 @@ 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()@@ -308,6 +306,7 @@ async def handle_memory_status("enabled": enabled,"proactive": proactive,"forbidden_enabled": _is_forbidden_enabled(config),+ "auto_memory_enabled": is_auto_memory_enabled(),}if detailed:@@ -366,20 +365,20 @@ async def handle_memory_status("dir": coding_dir if os.path.isdir(coding_dir) else "",}- memory_dir = os.path.join(workspace, "memory")- auto_files = _scan_md_files(memory_dir, "auto", workspace)- auto_total_chars = 0- for af in auto_files:- try:- text = Path(af["path"]).read_text(encoding="utf-8", errors="replace")- auto_total_chars += len(text)- except OSError:- pass- result["auto_memory"] = {- "files_count": len(auto_files),- "total_chars": auto_total_chars,- "dir": memory_dir if os.path.isdir(memory_dir) else "",- }+ # Auto-memory: unified with coding memory (same directory)+ if project_dir:+ # Auto-memory now uses coding memory directory (unified)+ result["auto_memory"] = {+ "files_count": len(coding_files),+ "total_chars": coding_total_chars,+ "dir": coding_dir if os.path.isdir(coding_dir) else "",+ }+ else:+ result["auto_memory"] = {+ "files_count": 0,+ "total_chars": 0,+ "dir": "",+ }engine = get_memory_engine(config)if engine in ("external", "both"):@@ -438,6 +437,26 @@ 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,+ )+ old = is_auto_memory_enabled()+ new = not old+ set_auto_memory_enabled(new)+ logger.info(+ "[memory_rpc] Toggle auto_memory_enabled: old=%s -> new=%s",+ old, new,+ )+ return {+ "key": key,+ "old_value": old,+ "new_value": new,+ "mode_affected": "global",+ "needs_restart": False, # No restart needed, config read each session+ }+return {"key": key,"old_value": False,@@ -470,7 +489,14 @@ async def handle_memory_open(}if project_dir:result["project_dir"] = project_dir- coding_dir = _get_coding_memory_dir(workspace, project_dir)- if os.path.isdir(coding_dir):+ # Unified: Auto-memory now uses coding memory directory+ coding_dir = _get_coding_memory_dir(workspace, project_dir)+ result["auto_memory_dir"] = coding_dir # Backward compatibilityresult["coding_memory_dir"] = coding_dir+ logger.info(+ "[memory_rpc] memory.open: project_dir=%s unified_memory_dir=%s",+ project_dir, coding_dir,+ )+ else:+ logger.info("[memory_rpc] memory.open: no project_dir provided")return resultdiff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.tsindex c5b4fdd30d..9aaf53bd68 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/memory.ts@@ -30,6 +30,7 @@ interface MemoryStatusResult {enabled: boolean;proactive: boolean;forbidden_enabled: boolean;+ auto_memory_enabled: boolean;index?: {available: boolean;provider?: string | null;@@ -76,6 +77,7 @@ interface MemoryOpenResult {project_memory_dir: string;project_dir?: string;coding_memory_dir?: string;+ auto_memory_dir?: string;}// ---------------------------------------------------------------------------@@ -381,6 +383,7 @@ async function showMemoryOverview(ctx: import("../types.js").CommandContext): Pritems.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({@@ -853,6 +856,7 @@ 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" },];async function toggleMemory(@@ -882,7 +886,9 @@ async function showToggleList(let current: boolean;if (t.key === "memory_enabled") current = payload.enabled;else if (t.key === "memory_proactive") current = payload.proactive;- else current = payload.forbidden_enabled;+ 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;return {label: t.key,@@ -962,6 +968,9 @@ async function openMemoryDir(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", {@@ -985,17 +994,145 @@ async function openMemoryDir(}}+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;++ try {+ // Get memory status and files+ const statusPayload = await ctx.request<MemoryStatusResult>("memory.status", {+ detailed: true,+ mode,+ });++ 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: "",+ });+ }++ // 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,+ })),+ },+ ],+ "local_command_memory",+ );+ selectedValue = answer?.selected_options?.[0]+ ? allOptions.find((opt) => opt.label === answer.selected_options[0])?.value+ : undefined;+ } catch {+ ctx.addItem(addInfo(ctx.sessionId, "Cancelled Memory interaction.", "i"));+ return;+ }++ if (!selectedValue) {+ ctx.addItem(addInfo(ctx.sessionId, "Cancelled Memory interaction.", "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"),+ );+ }+ } else {+ // Edit the selected memory file+ await editMemoryByPath(ctx, selectedValue);+ }+ } catch (err) {+ ctx.addItem(+ addError(ctx.sessionId, `Failed to show Memory interface: ${err instanceof Error ? err.message : String(err)}`),+ );+ }+}+export function createMemoryCommand(): SlashCommand {return {name: "memory",altNames: ["mem"],- description: "Edit memory files (list, edit, status, toggle, open)",+ description: "Manage memory settings and files (Auto-memory, edit, toggle, open)",usage: "/memory [list|edit|status|toggle|open] [args]",- example: "/memory edit",+ example: "/memory",kind: CommandKind.BUILT_IN,takesArgs: true,action: async (ctx) => {await showMemorySelector(ctx);+ await showAutoMemoryInteractive(ctx);},completion: async () => {return ["list", "edit", "status", "toggle", "open"];diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/types.tsindex 3a0fc1f5fd..8214dc5008 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts@@ -98,6 +98,8 @@ export interface CommandContext {) => void;enterStatusView?: (tab?: StatusViewTab) => void;openInEditor?: (filePath: string) => void;+ /** Open a folder in system file explorer (Windows: explorer, macOS: open -R, Linux: xdg-open) */+ openFolder?: (folderPath: string) => void;/** Enter FileViewer mode to view large content (e.g., formatted logs) */enterFileViewer?: (content: string, title: string, source: string) => void;/** Enter DiffViewer mode to browse git/turn diffs interactively */diff --git a/jiuwenswarm/channels/tui/frontend/src/core/utils/editor.ts b/jiuwenswarm/channels/tui/frontend/src/core/utils/editor.tsindex 2a74cfe6b0..fc91c2b790 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/utils/editor.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/utils/editor.ts@@ -1,5 +1,6 @@import { spawnSync, 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";const GUI_EDITORS = [@@ -127,4 +128,34 @@ function spawnFallback(filePath: string): SpawnSyncReturns<string | Buffer> {}return spawnSync("vi", [filePath], spawnOptions);+}++/**+ * Open a folder in the system file explorer (not an editor).+ * - Windows: explorer+ * - macOS: open -R (reveals in Finder)+ * - Linux: xdg-open+ */+export function openFolderInExplorer(folderPath: string): void {+ const spawnOptions: SpawnSyncOptions = { stdio: "inherit" };++ // Ensure folder exists before opening (explorer opens Documents if path doesn't exist)+ if (!existsSync(folderPath)) {+ try {+ mkdirSync(folderPath, { recursive: true });+ } catch {+ // Ignore errors - just try to open anyway+ }+ }++ 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 filediff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex 55ff4f7b7a..a31525c6d3 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -18,7 +18,7 @@ import * as fs from "node:fs";import * as path from "node:path";import * as os from "node:os";import type { CliPiAppState } from "../app-state.js";-import { openFileInEditor as openInExternalEditor } from "../core/utils/editor.js";+import { openFileInEditor as openInExternalEditor, openFolderInExplorer } from "../core/utils/editor.js";import {extractAttachmentsFromText,extractFilePathsFromPaste,@@ -2555,6 +2555,9 @@ export class AppScreen implements Component, Focusable {openInEditor: (filePath: string) => {openInExternalEditor(this.tui, filePath);},+ openFolder: (folderPath: string) => {+ openFolderInExplorer(folderPath);+ },enterFileViewer: (content, title, source) => {this.enterFileViewer(content, title, source);},@@ -5857,15 +5860,6 @@ export class AppScreen implements Component, Focusable {return false;}- const mouse = parseSgrMouseRelease(data);- if (mouse?.button === 0 && this.questionList !== null) {- const hit = this.questionOptionRows.find((entry) => entry.row === mouse.row);- if (hit) {- this.handleQuestionSelection(hit.value);- return true;- }- }-if (this.questionList !== null) {const question =snapshot.pendingQuestion.questions[this.activeQuestionIndex] ??diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.pyindex 8de632b9b2..d001cc2aaf 100644--- a/jiuwenswarm/common/config.py+++ b/jiuwenswarm/common/config.py@@ -123,6 +123,32 @@ 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", True))+ except Exception:+ # Default to True if config cannot be read+ return True+++def set_auto_memory_enabled(enabled: bool) -> None:+ """Set auto-memory enabled status in config.++ Args:+ enabled: True to enable, False to disable.+ """+ data = load_yaml_round_trip(CONFIG_YAML_PATH)+ data["auto_memory_enabled"] = enabled+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)++def load_yaml_round_trip(config_path: Path):"""ruamel 加载 config,保留注释与格式。"""rt = YAML()diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 91c28435d8..84c43ded84 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -64,6 +64,11 @@ symphony:flatten_tree: falsemax_exposure_depth: 1+# Auto Memory:对话结束后自动提取记忆,按项目隔离存储+# 存储路径:~/.jiuwenswarm/projects/{sanitized-project-path}/memory/+# 类似 Claude Code 的 auto-memory 功能+auto_memory_enabled: true+# 日志目录:~/.jiuwenswarm/agent/.logs/# gateway.log / channel.log / agent_server.log 按源码路径分流;full.log 为汇总。# level:未单独指定时的默认级别。console_level:控制台;可省略则用 level。diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex a7364ca676..c378659d3b 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -11,13 +11,17 @@from __future__ import annotationsimport asyncio+from dataclasses import dataclassimport inspectimport jsonimport loggingimport reimport timefrom pathlib import Path-from typing import Any, AsyncIterator, Tuple+from typing import TYPE_CHECKING, Any, AsyncIterator, Tuple++if TYPE_CHECKING:+ from openjiuwen.core.context_engine.engine import ContextEnginefrom datetime import datetime, timedelta, timezonefrom dotenv import load_dotenv@@ -35,7 +39,7 @@ from jiuwenswarm.server.runtime.session.session_history import (from jiuwenswarm.server.runtime.session.session_manager import SessionManagerfrom jiuwenswarm.server.runtime.skill.skill_manager import SkillManagerfrom jiuwenswarm.server.utils.utils import is_team_params-from jiuwenswarm.common.config import get_config+from jiuwenswarm.common.config import get_config, is_auto_memory_enabledfrom jiuwenswarm.extensions.registry import ExtensionRegistryfrom jiuwenswarm.common.schema.agent import AgentRequest, AgentResponse, AgentResponseChunkfrom jiuwenswarm.extensions.hook_event import AgentServerHookEvents@@ -48,6 +52,9 @@ from jiuwenswarm.common.utils import (reset_free_search_runtime_flags,)from jiuwenswarm.server.runtime.a2ui.integration import finalize_assistant_response_if_a2ui+from jiuwenswarm.agents.harness.common.auto_memory import (+ _execute_auto_memory_extraction,+)def _history_user_content(params: Any, query: Any) -> Any:@@ -108,6 +115,58 @@ def _contains_a2ui_marker(value: Any) -> bool:load_dotenv(dotenv_path=get_env_file(), override=True)reset_free_search_runtime_flags()++def _trigger_auto_memory_extraction(+ adapter: Any,+ request: AgentRequest,+ session_id: str,+ is_stream: bool = False,+) -> None:+ """Trigger auto memory extraction after conversation ends.++ Extracted helper to avoid code duplication between process_message and process_message_stream.++ Args:+ adapter: The AgentAdapter instance (e.g., JiuwenSwarmCodeAdapter).+ request: The agent request containing project_dir.+ session_id: The session ID for context retrieval.+ 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")++ # 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+ )+ )+logger = logging.getLogger(__name__)@@ -1311,6 +1370,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():+ _trigger_auto_memory_extraction(adapter, request, session_id, is_stream=False)+return resultasync def process_message_stream(@@ -1653,6 +1716,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():+ _trigger_auto_memory_extraction(adapter, request, session_id, is_stream=True)+yield AgentResponseChunk(request_id=rid,channel_id=cid,