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
feat(cli): /init command for coding
ldstyle85b73318caf4f
diff --git a/.gitignore b/.gitignoreindex 86c5967f0b..515234b470 100644--- a/.gitignore+++ b/.gitignore@@ -45,7 +45,10 @@ pnpm-debug.log**.swo.DS_Store.claude-CLAUDE.md+**/CLAUDE.md+**/CLAUDE.local.md+**/JIUWENCLAW.local.md+**/JIUWENCLAW.mdworkspace/agent-data.json# referencediff --git a/jiuwenclaw/agentserver/deep_agent/interface_code.py b/jiuwenclaw/agentserver/deep_agent/interface_code.pyindex fd6aaec306..d0e189400c 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_code.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_code.py@@ -6,6 +6,11 @@从 config.yaml::modes.code.rails/tools 读取配置列表,通过名字映射查找构建方法来注册。统一使用 create_deep_agent(),不再使用 create_code_agent()。++Code 模式独占逻辑全部收敛于此:+- LspRail、ProjectMemoryRail、CodingMemoryRail 等 code 专属 rail+- code_agent / explore_agent subagent 配置+- code 模式下 rail 生命周期(保留 SubagentRail、补充 ProjectMemoryRail 等)"""from __future__ import annotations@@ -15,13 +20,11 @@ import osfrom dataclasses import dataclassfrom typing import Any-from openjiuwen.core.foundation.tool import ToolCard+from openjiuwen.core.foundation.llm import Modelfrom openjiuwen.core.foundation.store.base_embedding import EmbeddingConfigfrom openjiuwen.core.runner import Runner-from openjiuwen.core.foundation.llm import Modelfrom openjiuwen.core.single_agent import AgentCard-from openjiuwen.core.sys_operation import SysOperation-from openjiuwen.harness import DeepAgent, VisionModelConfig, AudioModelConfig+from openjiuwen.harness import DeepAgentfrom openjiuwen.harness.factory import create_deep_agentfrom openjiuwen.harness.prompts import resolve_languagefrom openjiuwen.harness.rails import (@@ -33,27 +36,33 @@ from openjiuwen.harness.rails import (SecurityRail,TaskPlanningRail,)-from openjiuwen.harness.rails.lsp_rail import LspRail+from openjiuwen.harness.rails.coding_memory_rail import CodingMemoryRailfrom openjiuwen.harness.rails.context_engineering_rail import ContextEngineeringRailfrom openjiuwen.harness.rails.filesystem_rail import FileSystemRailfrom openjiuwen.harness.rails.heartbeat_rail import HeartbeatRail+from openjiuwen.harness.lsp import InitializeOptions+from openjiuwen.harness.rails.lsp_rail import LspRailfrom openjiuwen.harness.rails.memory_rail import MemoryRailfrom openjiuwen.harness.rails.subagent_rail import SubagentRailfrom openjiuwen.harness.schema.config import SubAgentConfig+from openjiuwen.harness.subagents.browser_agent import build_browser_agent_config+from openjiuwen.harness.subagents.code_agent import build_code_agent_configfrom openjiuwen.harness.subagents.explore_agent import build_explore_agent_configfrom openjiuwen.harness.subagents.plan_agent import build_plan_agent_configfrom openjiuwen.harness.tools import WebFetchWebpageTool, WebFreeSearchTool, WebPaidSearchToolfrom openjiuwen.harness.workspace.workspace import Workspace-from jiuwenclaw.agentserver.deep_agent.interface_deep import JiuWenClawDeepAdapter+from jiuwenclaw.agentserver.deep_agent.interface_deep import (+ JiuWenClawDeepAdapter,+ parse_int,+)from jiuwenclaw.agentserver.deep_agent.interrupt.interrupt_helpers import build_permission_railfrom jiuwenclaw.agentserver.deep_agent.prompt_builder import build_identity_promptfrom jiuwenclaw.agentserver.deep_agent.rails import (JiuClawContextEngineeringRail,- JiuClawStreamEventRail,- ResponsePromptRail,- RuntimePromptRail,+ ProjectMemoryRail,)+from jiuwenclaw.agentserver.memory.config import get_memory_modefrom jiuwenclaw.agentserver.permissions.core import init_permission_enginefrom jiuwenclaw.agentserver.tools import SkillToolkitfrom jiuwenclaw.config import get_config@@ -72,6 +81,8 @@ _RAIL_BUILD_NAMES: dict[str, str] = {"MemoryRail": "_build_memory_rail_via_config","ContextEngineeringRail": "_build_context_engineering_rail","SkillEvolutionRail": "_build_skill_evolution_rail_via_config",+ "ProjectMemoryRail": "_build_project_memory_rail",+ "CodingMemoryRail": "_build_coding_memory_rail",}_TOOL_BUILD_NAMES: dict[str, str] = {@@ -127,10 +138,21 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):继承 JiuWenClawDeepAdapter,只重写:- create_instance(): 统一使用 create_deep_agent(),不传多模态/上下文引擎参数- - _build_agent_rails(): 固定 Rails + 从 config.yaml 读取动态 Rails+ - _build_agent_rails(): 固定 Rails (含 LspRail/ProjectMemoryRail) + 从 config.yaml 读取动态 Rails- _get_tool_cards(): 从 config.yaml 读取动态 Tools+ - _build_configured_subagents(): 增加 code_agent / explore_agent+ - _update_rails_for_mode(): code 模式 rail 生命周期+ - _update_runtime_config(): 保留 ProjectMemoryRail 语言同步"""+ def __init__(self) -> None:+ super().__init__()+ # Code 模式专属 rails — 父类不定义这些属性+ self._lsp_rail: LspRail | None = None+ self._project_memory_rail: ProjectMemoryRail | None = None++ # ─── 初始化 ──────────────────────────────+async def create_instance(self, config: dict[str, Any] | None = None, *, mode: str = "code") -> None:"""初始化 DeepAgent 实例(code 模式).@@ -210,6 +232,8 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):await self.load_user_rails()+ # ─── Rails 构建 ──────────────────────────+def _build_agent_rails(self,config: dict[str, Any],@@ -217,7 +241,10 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):*,mode: str = "code",) -> list[Any]:- """Build rails for code mode: fixed rails + dynamic rails from config."""+ """Build rails for code mode: fixed rails + dynamic rails from config.++ Code 模式固定包含 LspRail 和 ProjectMemoryRail。+ """@dataclassclass _RailBuildInfo:@@ -228,12 +255,20 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):def __post_init__(self):self.params = self.params or {}- # 固定 Rails — 写死在代码中+ # 固定 Rails — code 模式特有:LspRail + ProjectMemoryRail 始终挂载+ # 已注册的固定 rail 名字集合,用于动态 rails 去重+ _fixed_rail_names = frozenset({+ "RuntimePromptRail", "ResponsePromptRail",+ "JiuClawStreamEventRail", "SecurityRail",+ "LspRail", "ProjectMemoryRail", "PermissionInterruptRail",+ })rail_infos = [_RailBuildInfo("_runtime_prompt_rail", self._build_runtime_prompt_rail),_RailBuildInfo("_response_prompt_rail", self._build_response_prompt_rail),_RailBuildInfo("_stream_event_rail", self._build_stream_event_rail),_RailBuildInfo("_security_rail", self._build_security_rail),+ _RailBuildInfo("_lsp_rail", self._build_lsp_rail_via_config),+ _RailBuildInfo("_project_memory_rail", self._build_project_memory_rail),_RailBuildInfo("_permission_rail",build_permission_rail,@@ -256,10 +291,17 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):]# 动态 Rails — 从 config.yaml::modes.code.rails 读取+ # 跳过已在固定列表中的 rail,避免重复注册mode_config = config_base.get("modes", {}).get("code", {})configured_rails = mode_config.get("rails") or []for rail_name in configured_rails:+ if rail_name in _fixed_rail_names:+ logger.info(+ "[JiuwenClawCodeAdapter] Rail %s already in fixed set, skipping dynamic registration",+ rail_name,+ )+ continuerail_instance = self._get_rail_build_func(rail_name)if rail_instance is None:logger.warning(@@ -326,6 +368,107 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):)return self._build_lsp_rail(workspace_dir=self._project_dir)+ # ─── Code 专属 Rail 构建 ────────────────++ def _build_lsp_rail(self, workspace_dir: str | None = None) -> LspRail | None:+ """Build LspRail(code 模式专属)."""+ try:+ lsp_rail = LspRail(InitializeOptions(cwd=workspace_dir))+ logger.info("[JiuwenClawCodeAdapter] LspRail create success")+ except Exception as exc:+ logger.warning("[JiuwenClawCodeAdapter] LspRail create failed: %s", exc)+ lsp_rail = None+ return lsp_rail++ def _build_coding_memory_rail(self) -> CodingMemoryRail | None:+ """构建 CodingMemoryRail(code_agent subagent 使用).++ Returns:+ CodingMemoryRail 实例,失败返回 None+ """+ try:+ config = get_config()+ embed_config = config.get("embed") if isinstance(config, dict) else None++ has_api_key = embed_config.get("embed_api_key") if isinstance(embed_config, dict) else None+ has_base_url = embed_config.get("embed_base_url") if isinstance(embed_config, dict) else None+ has_model = embed_config.get("embed_model") if isinstance(embed_config, dict) else None+ if not all([has_api_key, has_base_url, has_model]):+ logger.warning("[JiuwenClawCodeAdapter] CodingMemoryRail: no embedding config, skipping")+ return None++ language = config.get("preferred_language", "zh")+ coding_memory_dir = os.path.join(self._workspace_dir, "coding_memory")+ os.makedirs(coding_memory_dir, exist_ok=True)++ coding_memory_rail = CodingMemoryRail(+ coding_memory_dir=coding_memory_dir,+ embedding_config=EmbeddingConfig(+ model_name=embed_config.get("embed_model"),+ base_url=embed_config.get("embed_base_url"),+ api_key=embed_config.get("embed_api_key"),+ ),+ language="cn" if language == "zh" else "en",+ )+ logger.info("[JiuwenClawCodeAdapter] CodingMemoryRail create success")+ return coding_memory_rail++ except Exception as exc:+ logger.warning("[JiuwenClawCodeAdapter] CodingMemoryRail create failed: %s", exc)+ return None++ def _build_project_memory_rail(self) -> ProjectMemoryRail | None:+ """Build ProjectMemoryRail to auto-load JIUWENCLAW.md / CLAUDE.md etc.++ Code 模式专属 — 始终挂载。+ 确保能检索到 /init 命令创建 JIUWENCLAW.md 的目录(当前工作目录)。+ """+ try:+ workspace = self._workspace_dir or "./"+ language = self._resolve_runtime_language()+ raw_additional_dirs = self._instance_overrides.get(+ "project_memory_additional_directories",+ self._config_cache.get("project_memory", {}).get("additional_directories"),+ )+ if raw_additional_dirs is None:+ raw_additional_dirs = os.getenv("JIUWENCLAW_ADDITIONAL_DIRECTORIES", "")++ if isinstance(raw_additional_dirs, str):+ additional_dirs = [+ item.strip()+ for item in raw_additional_dirs.split(os.pathsep)+ if item.strip()+ ]+ elif isinstance(raw_additional_dirs, (list, tuple, set)):+ additional_dirs = [+ str(item).strip()+ for item in raw_additional_dirs+ if str(item).strip()+ ]+ else:+ additional_dirs = []++ rail = ProjectMemoryRail(+ workspace=workspace,+ language=language,+ additional_directories=tuple(additional_dirs),+ )+ logger.info(+ "[JiuwenClawCodeAdapter] ProjectMemoryRail create success "+ "(workspace=%s, language=%s, additional_dirs=%d)",+ workspace,+ language,+ len(additional_dirs),+ )+ return rail+ except Exception as exc: # noqa: BLE001+ logger.warning(+ "[JiuwenClawCodeAdapter] ProjectMemoryRail create failed: %s", exc,+ )+ return None++ # ─── 配置驱动的 Rail/Tool 构建代理 ──────────+def _build_skill_rail_via_config(self) -> Any:"""构建 SkillUseRail(从 config 读取参数)."""return self._build_skill_rail(@@ -345,6 +488,190 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):"""构建 SkillEvolutionRail."""return self._build_skill_evolution_rail(get_config())+ # ─── Subagent 配置 ──────────────────────────++ def _build_configured_subagents(+ self,+ model: Model,+ config: dict[str, Any],+ config_base: dict[str, Any] | None = None,+ ) -> list[Any] | None:+ """Build subagents for code mode: code_agent + explore_agent + browser_agent.++ Code 模式默认启用 explore_agent,并按配置启用 code_agent。+ """+ react_cfg = config if isinstance(config, dict) else {}+ subagents_cfg = react_cfg.get("subagents")++ resolved_language = self._resolve_runtime_language()+ workspace = self._workspace_dir or "./"+ subagents: list[Any] = []++ if isinstance(subagents_cfg, dict):+ # code_agent subagent — 按配置启用+ code_agent_cfg = subagents_cfg.get("code_agent")+ if self._is_subagent_enabled(code_agent_cfg):+ code_agent_rails = None+ if get_memory_mode(get_config()) == "local":+ coding_memory_rail = self._build_coding_memory_rail()+ if coding_memory_rail is not None:+ # FileSystemRail is default rail for code_agent;+ # passing rails overrides defaults, must include it explicitly+ code_agent_rails = [FileSystemRail(), coding_memory_rail]+ subagents.append(+ build_code_agent_config(+ model,+ workspace=workspace,+ language=resolved_language,+ rails=code_agent_rails,+ max_iterations=parse_int(+ code_agent_cfg.get("max_iterations"),+ react_cfg.get("max_iterations", 15),+ ),+ )+ )++ # browser_agent+ browser_agent_cfg = subagents_cfg.get("browser_agent")+ browser_enabled = self._browser_runtime_enabled()+ if browser_enabled:+ if not str(os.getenv("BROWSER_DRIVER") or "").strip():+ os.environ["BROWSER_DRIVER"] = "managed"+ logger.info(+ "[JiuwenClawCodeAdapter] browser subagent enabled without BROWSER_DRIVER; "+ "defaulting to managed mode"+ )+ if not str(os.getenv("BROWSER_MANAGED_BINARY") or "").strip():+ chrome_path = self._resolve_managed_browser_binary_from_config()+ if chrome_path:+ os.environ["BROWSER_MANAGED_BINARY"] = chrome_path+ logger.info(+ "[JiuwenClawCodeAdapter] using browser.chrome_path for managed browser: %s",+ chrome_path,+ )+ subagents.append(+ build_browser_agent_config(+ model,+ workspace=workspace,+ language=resolved_language,+ max_iterations=parse_int(+ browser_agent_cfg.get("max_iterations") if isinstance(browser_agent_cfg, dict) else None,+ react_cfg.get("max_iterations", 15),+ )+ )+ )++ # explore_agent 是 code 模式的核心子代理 — 默认启用+ explore_agent_cfg = subagents_cfg.get("explore_agent") if isinstance(subagents_cfg, dict) else None+ if self._is_subagent_default_enabled(explore_agent_cfg):+ subagents.append(+ build_explore_agent_config(+ model=model,+ workspace=workspace,+ language=resolved_language,+ max_iterations=parse_int(+ explore_agent_cfg.get("max_iterations") if isinstance(explore_agent_cfg, dict) else None,+ react_cfg.get("max_iterations", 15),+ ),+ )+ )++ return subagents or None++ # ─── Rail 生命周期(mode切换) ───────────────────++ async def _update_rails_for_mode(self, mode: str) -> None:+ """Code 模式下的 rail 生命周期管理.++ code.normal / code.plan 等模式:+ - 保留 SubagentRail(主 Agent 通过 task_tool 派发 explore/plan 子代理)+ - 保留 ProjectMemoryRail(code 模式始终挂载)+ - 卸载 TaskPlanningRail、SkillEvolutionRail+ - 按 config 注册/卸载 MemoryRail+ """+ # 卸载非 code 专属 rails(SubagentRail 在 code 模式保留)+ rail_specs = (+ ("_task_planning_rail", "TaskPlanningRail"),+ ("_skill_evolution_rail", "SkillEvolutionRail"),+ )++ for attr, label in rail_specs:+ rail = getattr(self, attr, None)+ if rail is not None:+ await self._instance.unregister_rail(rail)+ setattr(self, attr, None)+ logger.info(+ "[JiuwenClawCodeAdapter] %s unregistered for %s mode",+ label, mode,+ )++ # code 模式保留 SubagentRail;若缺失则补充注册+ if self._subagent_rail is None:+ self._subagent_rail = self._build_subagent_rail()+ if self._subagent_rail is not None:+ await self._instance.register_rail(self._subagent_rail)+ logger.info(+ "[JiuwenClawCodeAdapter] SubagentRail (re)registered for %s",+ mode,+ )++ # code 模式保留 ProjectMemoryRail;若缺失则补充注册+ if self._project_memory_rail is None:+ self._project_memory_rail = self._build_project_memory_rail()+ if self._project_memory_rail is not None:+ await self._instance.register_rail(self._project_memory_rail)+ logger.info(+ "[JiuwenClawCodeAdapter] ProjectMemoryRail (re)registered for %s",+ mode,+ )++ # code 模式,根据 config 选择是否注册或者卸载 memory rail+ await self._handle_memory_rail_by_config("fast")++ # ─── Runtime config ──────────────────────────++ async def _update_runtime_config(self, runtime_config: "JiuWenClawDeepAdapter._RuntimeConfig") -> None:+ """Code 模式 runtime config: ProjectMemoryRail 语言同步 + rail 模式切换."""+ if self._instance is None:+ raise RuntimeError("JiuwenClawCodeAdapter 未初始化,请先调用 create_instance()")++ resolved_language = self._resolve_runtime_language()+ resolved_channel = str(runtime_config.channel_id or+ self._resolve_prompt_channel(runtime_config.session_id) or "web").strip() or "web"+ if self._runtime_prompt_rail:+ self._runtime_prompt_rail.set_language(resolved_language)+ self._runtime_prompt_rail.set_channel(resolved_channel)+ self._runtime_prompt_rail.set_trusted_dirs(runtime_config.trusted_dirs)+ self._write_runtime_state(mode=runtime_config.mode, language=resolved_language, channel=resolved_channel)++ # ProjectMemoryRail 语言同步 + trusted_dirs 注入+ if self._project_memory_rail is not None:+ self._project_memory_rail.set_language(resolved_language)+ # trusted_dirs 来自 CLI 端的 trusted_dirs / workspace-dir,+ # 包含用户项目目录(即 /init 写 JIUWENCLAW.md 的目录)+ if runtime_config.trusted_dirs:+ self._project_memory_rail.set_additional_directories(+ runtime_config.trusted_dirs,+ )++ # code 模式始终走 _update_rails_for_mode 的 code 逻辑+ await self._update_rails_for_mode(runtime_config.mode)+ await self._update_tools_for_mode(runtime_config.mode, runtime_config.session_id, runtime_config.request_id)+ await self._update_session_tools(+ runtime_config.session_id,+ runtime_config.request_id,+ channel_id=runtime_config.channel_id,+ )+ self._refresh_acp_runtime_tools(+ runtime_config.session_id,+ runtime_config.request_id,+ runtime_config.channel_id,+ runtime_config.request_metadata,+ )+ self._update_prompt_for_mode(runtime_config.mode, resolved_language)++ # ─── Tools 构建 ──────────────────────────+async def _get_tool_cards(self, agent_id: str) -> list[Any]:"""Get tool cards for code mode — from config.yaml::modes.code.tools."""diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.pyindex 72f09d0329..a6c8f07f73 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py@@ -49,20 +49,16 @@ from openjiuwen.harness import (VisionModelConfig,)from openjiuwen.harness.factory import create_deep_agent-from openjiuwen.harness.lsp import InitializeOptionsfrom openjiuwen.harness.prompts import resolve_languagefrom openjiuwen.harness.rails import SkillUseRail, TaskPlanningRail, SecurityRail, SkillEvolutionRailfrom openjiuwen.harness.rails.subagent_rail import SubagentRail-from openjiuwen.harness.rails.lsp_rail import LspRailfrom openjiuwen.harness.rails.context_engineer.context_assemble_rail import ContextAssembleRailfrom openjiuwen.harness.rails.context_engineer.context_processor_rail import ContextProcessorRailfrom openjiuwen.harness.rails.filesystem_rail import FileSystemRailfrom openjiuwen.harness.rails.heartbeat_rail import HeartbeatRailfrom openjiuwen.agent_evolving.signal import SignalDetectorfrom openjiuwen.harness.rails.memory_rail import MemoryRail-from openjiuwen.harness.rails.coding_memory_rail import CodingMemoryRailfrom openjiuwen.harness.subagents.browser_agent import build_browser_agent_config-from openjiuwen.harness.subagents.code_agent import build_code_agent_config, create_code_agentfrom openjiuwen.harness.subagents.research_agent import build_research_agent_configfrom openjiuwen.harness.tools import (WebFetchWebpageTool,@@ -208,7 +204,7 @@ _ACP_BLOCKED_DEFAULT_TOOL_NAMES = frozenset()-def _parse_int(value: Any, default: int) -> int:+def parse_int(value: Any, default: int) -> int:"""Parse integer-like values safely."""try:if value is None or value == "":@@ -357,7 +353,6 @@ class JiuWenClawDeepAdapter:self._memory_rail: MemoryRail | None = Noneself._external_memory_rail: Any = Noneself._external_memory_rail_registered: bool = False- self._lsp_rail: LspRail | None = Noneself._heartbeat_rail: HeartbeatRail | None = Noneself._skill_evolution_rail: SkillEvolutionRail | None = Noneself._subagent_rail: SubagentRail | None = None@@ -517,13 +512,20 @@ class JiuWenClawDeepAdapter:"""Treat only explicit `enabled: true` as enabled."""return isinstance(subagent_cfg, dict) and bool(subagent_cfg.get("enabled", False))+ @staticmethod+ def _is_subagent_default_enabled(subagent_cfg: Any) -> bool:+ """Default-enabled subagent: enabled unless explicitly set to false."""+ if not isinstance(subagent_cfg, dict):+ return True # no config → default enabled+ return subagent_cfg.get("enabled", True) is not False+def _build_configured_subagents(self,model: Model,config: dict[str, Any],config_base: dict[str, Any] | None = None,) -> list[Any] | None:- """Build configured code/research subagents plus default browser subagent."""+ """Build configured research + browser subagents (agent 模式)."""react_cfg = config if isinstance(config, dict) else {}subagents_cfg = react_cfg.get("subagents")@@ -532,27 +534,6 @@ class JiuWenClawDeepAdapter:subagents: list[Any] = []if isinstance(subagents_cfg, dict):- code_agent_cfg = subagents_cfg.get("code_agent")- if self._is_subagent_enabled(code_agent_cfg):- code_agent_rails = None- if get_memory_mode(get_config()) == "local":- coding_memory_rail = self._build_coding_memory_rail()- if coding_memory_rail is not None:- # FileSystemRail 是 create_code_agent 的默认 rail,传 rails 会覆盖默认值,需显式带上- code_agent_rails = [FileSystemRail(), coding_memory_rail]- subagents.append(- build_code_agent_config(- model,- workspace=workspace,- language=resolved_language,- rails=code_agent_rails,- max_iterations=_parse_int(- code_agent_cfg.get("max_iterations"),- react_cfg.get("max_iterations", 15),- ),- )- )-research_agent_cfg = subagents_cfg.get("research_agent")if self._is_subagent_enabled(research_agent_cfg):subagents.append(@@ -560,7 +541,7 @@ class JiuWenClawDeepAdapter:model,workspace=workspace,language=resolved_language,- max_iterations=_parse_int(+ max_iterations=parse_int(research_agent_cfg.get("max_iterations"),react_cfg.get("max_iterations", 15),),@@ -589,7 +570,7 @@ class JiuWenClawDeepAdapter:model,workspace=workspace,language=resolved_language,- max_iterations=_parse_int(+ max_iterations=parse_int(browser_agent_cfg.get("max_iterations") if isinstance(browser_agent_cfg, dict) else None,react_cfg.get("max_iterations", 15),)@@ -829,7 +810,7 @@ class JiuWenClawDeepAdapter:api_key=api_key,base_url=base_url,model=model_name,- max_retries=_parse_int(os.getenv("VISION_MAX_RETRIES"), 3),+ max_retries=parse_int(os.getenv("VISION_MAX_RETRIES"), 3),)def _build_audio_model_config(@@ -868,9 +849,9 @@ class JiuWenClawDeepAdapter:config_kwargs: dict[str, Any] = {"api_key": api_key,"base_url": base_url,- "max_retries": _parse_int(os.getenv("AUDIO_MAX_RETRIES"), 3),- "http_timeout": _parse_int(os.getenv("AUDIO_HTTP_TIMEOUT"), 20),- "max_audio_bytes": _parse_int(+ "max_retries": parse_int(os.getenv("AUDIO_MAX_RETRIES"), 3),+ "http_timeout": parse_int(os.getenv("AUDIO_HTTP_TIMEOUT"), 20),+ "max_audio_bytes": parse_int(os.getenv("AUDIO_MAX_AUDIO_BYTES"),25 * 1024 * 1024,),@@ -1395,59 +1376,6 @@ class JiuWenClawDeepAdapter:memory_rail = Nonereturn memory_rail- def _build_coding_memory_rail(self) -> CodingMemoryRail | None:- """构建 CodingMemoryRail.-- Returns:- CodingMemoryRail 实例,失败返回 None- """- try:- config = get_config()- embed_config = config.get("embed") if isinstance(config, dict) else None-- # 检查 embedding 配置- has_api_key = embed_config.get("embed_api_key") if isinstance(embed_config, dict) else None- has_base_url = embed_config.get("embed_base_url") if isinstance(embed_config, dict) else None- has_model = embed_config.get("embed_model") if isinstance(embed_config, dict) else None- if not all([has_api_key, has_base_url, has_model]):- logger.warning("[JiuWenClawDeepAdapter] CodingMemoryRail: no embedding config, skipping")- return None-- # 获取语言和 workspace 目录- language = config.get("preferred_language", "zh")- coding_memory_dir = os.path.join(self._workspace_dir, "coding_memory")-- # 确保目录存在- os.makedirs(coding_memory_dir, exist_ok=True)-- # 创建 CodingMemoryRail- coding_memory_rail = CodingMemoryRail(- coding_memory_dir=coding_memory_dir,- embedding_config=EmbeddingConfig(- model_name=embed_config.get("embed_model"),- base_url=embed_config.get("embed_base_url"),- api_key=embed_config.get("embed_api_key"),- ),- language="cn" if language == "zh" else "en",- )- logger.info("[JiuWenClawDeepAdapter] CodingMemoryRail create success")- return coding_memory_rail-- except Exception as exc:- logger.warning("[JiuWenClawDeepAdapter] CodingMemoryRail create failed: %s", exc)- return None-- @staticmethod- def _build_lsp_rail(workspace_dir: str = None) -> LspRail | None:- """Build LspRail."""- try:- lsp_rail = LspRail(InitializeOptions(cwd=workspace_dir))- logger.info("[JiuWenClawDeepAdapter] LspRail create success")- except Exception as exc:- logger.warning("[JiuWenClawDeepAdapter] LspRail create failed: %s", exc)- lsp_rail = None- return lsp_rail-def _build_heartbeat_rail(self) -> HeartbeatRail | None:"""Build HeartbeatRail."""try:@@ -1522,10 +1450,6 @@ class JiuWenClawDeepAdapter:# MemoryRail 不在冷启动时挂载,由 _update_rails_for_mode 按 mode 按需注册/注销- # LspRail 仅在 code 模式下挂载- if mode == "code":- rail_infos.append(_RailBuildInfo("_lsp_rail", self._build_lsp_rail))-if self._filesystem_rail_enabled_for_profile():rail_infos.insert(1, _RailBuildInfo("_filesystem_rail", self._build_filesystem_rail))else:@@ -1651,8 +1575,6 @@ class JiuWenClawDeepAdapter:rails_list.append(self._context_processor_rail)if self._memory_rail is not None:rails_list.append(self._memory_rail)- if self._lsp_rail is not None:- rails_list.append(self._lsp_rail)if self._avatar_rail is not None:rails_list.append(self._avatar_rail)if self._permission_rail is not None:@@ -1805,7 +1727,7 @@ class JiuWenClawDeepAdapter:- agent_name: Agent 名称,默认 "main_agent"。- workspace_dir: 工作区目录,默认 "workspace/agent"。- 其余字段透传给 DeepAgentConfig。- mode: 实例化模式,支持 "claw"(默认,使用 create_deep_agent)和 "code"(使用 create_code_agent)。+ mode: 实例化模式,默认 "agent.plan",使用 create_deep_agent。"""await self.set_checkpoint()@@ -1868,16 +1790,13 @@ class JiuWenClawDeepAdapter:language=self._resolve_runtime_language(),)- if mode == "code":- self._instance = create_code_agent(**common_kwargs)- else:- self._instance = create_deep_agent(- **common_kwargs,- context_engine_config=_deep_agent_context_engine_config(config),- vision_model_config=self._vision_model_config,- audio_model_config=self._audio_model_config,- completion_timeout=config.get("completion_timeout", 3600.0),- )+ self._instance = create_deep_agent(+ **common_kwargs,+ context_engine_config=_deep_agent_context_engine_config(config),+ vision_model_config=self._vision_model_config,+ audio_model_config=self._audio_model_config,+ completion_timeout=config.get("completion_timeout", 3600.0),+ )self._registered_mcp_server_ids.clear()self._registered_mcp_servers.clear()await self._register_mcp_servers_from_config(config_base, tag=f"agent.{mode}")@@ -2016,10 +1935,8 @@ class JiuWenClawDeepAdapter:"""按 mode 注册或卸载 rails。"""if mode == "agent.plan":await self._update_plan_mode_rails()- elif mode in ("code.plan", "code.normal"):- logger.info("[JiuWenClawDeepAdapter] skip agent mode rail update for code mode")else:- await self._update_agent_mode_rails()+ await self._update_agent_mode_rails(mode) # 透传 modeasync def _update_plan_mode_rails(self) -> None:"""plan 模式:注册 plan 专属 rails,卸载 agent 专属资源。"""@@ -2075,19 +1992,27 @@ class JiuWenClawDeepAdapter:await self._instance.register_rail(self._subagent_rail)logger.info("[JiuWenClawDeepAdapter] SubagentRail registered for plan mode")- async def _update_agent_mode_rails(self) -> None:+ async def _update_agent_mode_rails(self, mode: str | None = None) -> None:"""agent 模式:卸载 plan 专属 rails,按需注册 agent 专属 rails。"""- for attr, label in (- ("_task_planning_rail", "TaskPlanningRail"),- ("_skill_evolution_rail", "SkillEvolutionRail"),- ("_subagent_rail", "SubagentRail"),- ):+ # 卸载 plan 专属 rails+ rail_specs = (+ ("_task_planning_rail", "TaskPlanningRail"),+ ("_skill_evolution_rail", "SkillEvolutionRail"),+ ("_subagent_rail", "SubagentRail"),+ )++ for attr, label in rail_specs:rail = getattr(self, attr)if rail is not None:await self._instance.unregister_rail(rail)setattr(self, attr, None)- logger.info("[JiuWenClawDeepAdapter] %s unregistered for agent mode", label)- # agent 模式,根据config选择是否注册或者卸载memory rail+ logger.info(+ "[JiuWenClawDeepAdapter] %s unregistered for %s mode",+ label,+ mode or "agent",+ )++ # agent 模式,根据 config 选择是否注册或者卸载 memory railawait self._handle_memory_rail_by_config("fast")# 外接记忆 rail(mode-independent,注册一次,跨 reload 持久)await self._handle_external_memory_rail_by_config()diff --git a/jiuwenclaw/agentserver/deep_agent/rails/__init__.py b/jiuwenclaw/agentserver/deep_agent/rails/__init__.pyindex e8b3a19cda..5636d4bae1 100644--- a/jiuwenclaw/agentserver/deep_agent/rails/__init__.py+++ b/jiuwenclaw/agentserver/deep_agent/rails/__init__.py@@ -5,6 +5,7 @@from jiuwenclaw.agentserver.deep_agent.rails.context_engineering_rail_ext import JiuClawContextEngineeringRailfrom jiuwenclaw.agentserver.deep_agent.rails.permission_rail import PermissionInterruptRailfrom jiuwenclaw.agentserver.deep_agent.rails.avatar_rail import AvatarPromptRail+from jiuwenclaw.agentserver.deep_agent.rails.project_memory_rail import ProjectMemoryRailfrom jiuwenclaw.agentserver.deep_agent.rails.response_prompt_rail import ResponsePromptRailfrom jiuwenclaw.agentserver.deep_agent.rails.runtime_prompt_rail import RuntimePromptRailfrom jiuwenclaw.agentserver.deep_agent.rails.team_member_skill_toolkit_rail import (@@ -17,6 +18,7 @@ __all__ = ["JiuClawStreamEventRail","PermissionInterruptRail","AvatarPromptRail",+ "ProjectMemoryRail","ResponsePromptRail","RuntimePromptRail","MemberSkillToolkitRail",diff --git a/jiuwenclaw/agentserver/deep_agent/rails/project_memory/__init__.py b/jiuwenclaw/agentserver/deep_agent/rails/project_memory/__init__.pynew file mode 100644index 0000000000..b1ff51df9a--- /dev/null+++ b/jiuwenclaw/agentserver/deep_agent/rails/project_memory/__init__.py@@ -0,0 +1,43 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Project memory helpers (file discovery + PromptSection factory)."""+from jiuwenclaw.agentserver.deep_agent.rails.project_memory.files import (+ ADDITIONAL_DIRECTORIES_ENV,+ DEFAULT_MAX_CHARS,+ LOCAL_MEMORY_FILES,+ LoadedMemoryFile,+ MANAGED_MEMORY_FILES,+ MANAGED_MEMORY_GLOBS,+ PROJECT_MEMORY_FILES,+ PROJECT_MEMORY_GLOBS,+ PROJECT_ROOT_MARKERS,+ USER_MEMORY_FILES,+ USER_MEMORY_GLOBS,+ clear_project_memory_cache,+ discover_and_load_memory_files,+ find_project_root,+ merge_memory_content,+)+from jiuwenclaw.agentserver.deep_agent.rails.project_memory.section import (+ SECTION_NAME,+ build_project_memory_section,+)++__all__ = [+ "ADDITIONAL_DIRECTORIES_ENV",+ "LoadedMemoryFile",+ "discover_and_load_memory_files",+ "find_project_root",+ "merge_memory_content",+ "PROJECT_ROOT_MARKERS",+ "PROJECT_MEMORY_FILES",+ "PROJECT_MEMORY_GLOBS",+ "LOCAL_MEMORY_FILES",+ "USER_MEMORY_FILES",+ "USER_MEMORY_GLOBS",+ "MANAGED_MEMORY_FILES",+ "MANAGED_MEMORY_GLOBS",+ "clear_project_memory_cache",+ "DEFAULT_MAX_CHARS",+ "SECTION_NAME",+ "build_project_memory_section",+]diff --git a/jiuwenclaw/agentserver/deep_agent/rails/project_memory/files.py b/jiuwenclaw/agentserver/deep_agent/rails/project_memory/files.pynew file mode 100644index 0000000000..2da1b89840--- /dev/null+++ b/jiuwenclaw/agentserver/deep_agent/rails/project_memory/files.py@@ -0,0 +1,945 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Project memory file discovery + merge.++Used by :class:`ProjectMemoryRail` to collect JiuwenClaw project-memory files,+expand ``@include`` references, apply frontmatter ``paths:`` scoping against+the current workspace/cwd, and+merge the effective sources into a single prompt section.++Current scope+-------------+* multi-layer discovery: managed -> user -> project (root -> cwd) -> local+* fixed-filename + glob-based scanning (+ optional additional directories)+* nested git worktree handling+* symlink-safe de-duplication+* ``@include`` expansion on standalone text lines+* frontmatter stripping + workspace-scoped ``paths:`` conditional rules+* cache with explicit invalidation and filesystem snapshot fallback+* soft char-cap with truncation marker++Out of current scope (maybe defer to later extensions)+------------------------------------------------+* HTML block-comment stripping+* nested-memory attachment pipeline+* approval-gated external includes+"""+from __future__ import annotations++import functools+import glob as _glob+import os+import posixpath+import re+import shutil+import subprocess+from dataclasses import dataclass, field+from fnmatch import fnmatchcase+from pathlib import Path+from threading import RLock+from typing import Iterable, Optional++from jiuwenclaw.utils import logger++# ---------------------------------------------------------------------------+# Discovery configuration+# ---------------------------------------------------------------------------++PROJECT_ROOT_MARKERS: tuple[str, ...] = (+ ".git",+ ".jiuwen",+ ".claude",+ "pyproject.toml",+ "package.json",+ "Cargo.toml",+ "go.mod",+ "pom.xml",+)++PROJECT_MEMORY_FILES: tuple[tuple[str, str], ...] = (+ ("JIUWENCLAW.md", "project"),+ ("CLAUDE.md", "project"),+ (".jiuwen/JIUWENCLAW.md", "project"),+ (".claude/CLAUDE.md", "project"),+)++LOCAL_MEMORY_FILES: tuple[tuple[str, str], ...] = (+ ("JIUWENCLAW.local.md", "local"),+ ("CLAUDE.local.md", "local"),+)++PROJECT_MEMORY_GLOBS: tuple[str, ...] = (+ ".jiuwen/rules/*.md",+ ".claude/rules/*.md",+)++USER_MEMORY_FILES: tuple[str, ...] = (+ "~/.jiuwen/JIUWENCLAW.md",+ "~/.claude/CLAUDE.md",+)++USER_MEMORY_GLOBS: tuple[str, ...] = (+ "~/.jiuwen/rules/*.md",+ "~/.claude/rules/*.md",+)++MANAGED_MEMORY_FILES: tuple[str, ...] = (+ "/etc/jiuwen/JIUWENCLAW.md",+)++MANAGED_MEMORY_GLOBS: tuple[str, ...] = (+ "/etc/jiuwen/rules/*.md",+)++ADDITIONAL_DIRECTORIES_ENV = "JIUWENCLAW_ADDITIONAL_DIRECTORIES"+DEFAULT_MAX_CHARS = 60_000++# Priority: smaller = applied first (later = semantically override).+PRIORITY: dict[str, int] = {+ "managed": 10,+ "user": 20,+ "project": 30,+ "local": 40,+}++# Closing ``---`` may be followed by a newline OR be the end of file.+_FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?\n)---\s*(?:\n|\Z)", re.DOTALL)+_FENCE_RE = re.compile(r"^\s*(```|~~~)")+++# ---------------------------------------------------------------------------+# Data classes / cache entries+# ---------------------------------------------------------------------------+++@dataclass+class LoadedMemoryFile:+ """A single memory file loaded from disk."""++ path: str+ kind: str+ content: str+ frontmatter: dict = field(default_factory=dict)+ priority: int = 30+++@dataclass(frozen=True)+class GitWorktreeInfo:+ worktree_root: Path+ canonical_root: Path+++@dataclass(frozen=True)+class _DiscoveryCacheEntry:+ files: tuple[LoadedMemoryFile, ...]+ watch_snapshot: tuple[tuple[str, bool, bool, int | None, int | None], ...]+++_DISCOVERY_CACHE: dict[tuple[str, str, tuple[str, ...]], _DiscoveryCacheEntry] = {}+_CACHE_LOCK = RLock()+++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------+++def clear_project_memory_cache(workspace: str | None = None) -> None:+ """Clear cached discovery results.++ When ``workspace`` is provided, only cache entries rooted at that workspace+ are removed; otherwise the full cache is cleared.+ """+ with _CACHE_LOCK:+ if workspace is None:+ _DISCOVERY_CACHE.clear()+ return+ workspace_key = _safe_resolve(Path(workspace))+ stale_keys = [key for key in _DISCOVERY_CACHE if key[0] == workspace_key]+ for key in stale_keys:+ _DISCOVERY_CACHE.pop(key, None)+++def find_project_root(cwd: str) -> Optional[Path]:+ """Walk up from ``cwd`` to find the first directory containing a root marker."""+ try:+ current = Path(cwd).resolve()+ except (OSError, ValueError, TypeError):+ return None+ for parent in [current, *current.parents]:+ for marker in PROJECT_ROOT_MARKERS:+ try:+ if (parent / marker).exists():+ return parent+ except OSError:+ continue+ return None+++def discover_and_load_memory_files(+ *,+ workspace: str,+ target_path: str | None = None,+ additional_directories: Iterable[str] | None = None,+) -> list[LoadedMemoryFile]:+ """Discover and load every applicable memory file.++ Order (low priority first):+ managed -> user -> project (root -> cwd, each directory contributes) -> local+ """+ workspace_path = Path(workspace)+ workspace_key = _safe_resolve(workspace_path)+ target_key = _safe_resolve(Path(target_path or workspace_key))+ normalized_additional_dirs = _normalize_additional_directories(+ additional_directories,+ workspace=Path(workspace_key),+ )+ cache_key = (workspace_key, target_key, normalized_additional_dirs)++ with _CACHE_LOCK:+ cached = _DISCOVERY_CACHE.get(cache_key)+ if cached is not None and cached.watch_snapshot == _build_watch_snapshot(+ path for path, *_ in cached.watch_snapshot+ ):+ return list(cached.files)++ files: list[LoadedMemoryFile] = []+ seen: set[str] = set()+ watch_paths: set[str] = set()++ for raw in MANAGED_MEMORY_FILES:+ _try_load_single(+ raw,+ "managed",+ files,+ seen,+ target_path=target_key,+ watch_paths=watch_paths,+ )+ _scan_absolute_globs(+ MANAGED_MEMORY_GLOBS,+ kind="managed",+ out=files,+ seen=seen,+ target_path=target_key,+ watch_paths=watch_paths,+ )++ for raw in USER_MEMORY_FILES:+ _try_load_single(+ raw,+ "user",+ files,+ seen,+ target_path=target_key,+ watch_paths=watch_paths,+ )+ _scan_absolute_globs(+ USER_MEMORY_GLOBS,+ kind="user",+ out=files,+ seen=seen,+ target_path=target_key,+ watch_paths=watch_paths,+ )++ project_root = find_project_root(workspace_key)+ if project_root is not None:+ try:+ cwd = Path(workspace_key)+ except (OSError, ValueError, TypeError):+ cwd = project_root++ worktree_info = _detect_git_worktree(cwd)+ scan_root = project_root+ if (+ worktree_info is not None+ and worktree_info.canonical_root != worktree_info.worktree_root+ and _is_relative_to(project_root, worktree_info.canonical_root)+ ):+ scan_root = worktree_info.canonical_root++ walk_dirs: list[Path] = []+ current = cwd+ while True:+ walk_dirs.append(current)+ if current == scan_root or current.parent == current:+ break+ current = current.parent+ walk_dirs.reverse()++ for d in walk_dirs:+ watch_paths.add(_safe_resolve(d))+ skip_project = _should_skip_project_dir(d, worktree_info)+ if not skip_project:+ _scan_relative_files(+ base_dir=d,+ entries=PROJECT_MEMORY_FILES,+ out=files,+ seen=seen,+ target_path=target_key,+ watch_paths=watch_paths,+ )+ _scan_relative_globs(+ base_dir=d,+ patterns=PROJECT_MEMORY_GLOBS,+ kind="project",+ out=files,+ seen=seen,+ target_path=target_key,+ watch_paths=watch_paths,+ )+ _scan_relative_files(+ base_dir=d,+ entries=LOCAL_MEMORY_FILES,+ out=files,+ seen=seen,+ target_path=target_key,+ watch_paths=watch_paths,+ )++ for raw_dir in normalized_additional_dirs:+ extra_dir = Path(raw_dir)+ watch_paths.add(_safe_resolve(extra_dir))+ _scan_relative_files(+ base_dir=extra_dir,+ entries=PROJECT_MEMORY_FILES,+ out=files,+ seen=seen,+ target_path=target_key,+ watch_paths=watch_paths,+ )+ _scan_relative_globs(+ base_dir=extra_dir,+ patterns=PROJECT_MEMORY_GLOBS,+ kind="project",+ out=files,+ seen=seen,+ target_path=target_key,+ watch_paths=watch_paths,+ )+ _scan_relative_files(+ base_dir=extra_dir,+ entries=LOCAL_MEMORY_FILES,+ out=files,+ seen=seen,+ target_path=target_key,+ watch_paths=watch_paths,+ )++ # Stable sort by priority (preserves discovery order within same priority).+ files.sort(key=lambda f: f.priority)+ snapshot = _build_watch_snapshot(watch_paths)+ with _CACHE_LOCK:+ _DISCOVERY_CACHE[cache_key] = _DiscoveryCacheEntry(+ files=tuple(files),+ watch_snapshot=snapshot,+ )+ return list(files)+++def merge_memory_content(+ files: Iterable[LoadedMemoryFile],+ *,+ max_chars: int = DEFAULT_MAX_CHARS,+) -> str:+ """Merge files into a single text block with per-file headers.++ Applies a soft cap at ``max_chars`` and appends a truncation marker+ when exceeded.+ """+ parts: list[str] = []+ total = 0+ truncated_at: Optional[str] = None+ for f in files:+ chunk = f"### {f.kind} memory -- {_short(f.path)}\n{f.content}\n"+ if total + len(chunk) > max_chars:+ remaining = max_chars - total+ if remaining > 200:+ parts.append(chunk[:remaining])+ truncated_at = f.path+ break+ parts.append(chunk)+ total += len(chunk)+ merged = "\n".join(parts).strip()+ if truncated_at is not None:+ logger.warning(+ "[project_memory] merged content exceeded max_chars=%d; truncated at %s",+ max_chars,+ truncated_at,+ )+ merged += "\n\n<!-- project memory truncated (> max_chars) -->"+ return merged+++# ---------------------------------------------------------------------------+# Internal helpers+# ---------------------------------------------------------------------------+++def _normalize_additional_directories(+ additional_directories: Iterable[str] | None,+ *,+ workspace: Path | None = None,+) -> tuple[str, ...]:+ if additional_directories is None:+ env_value = os.getenv(ADDITIONAL_DIRECTORIES_ENV, "")+ additional_directories = [+ item.strip()+ for item in env_value.split(os.pathsep)+ if item.strip()+ ]+ result: list[str] = []+ seen: set[str] = set()+ for raw in additional_directories:+ candidate = Path(os.path.expanduser(str(raw)))+ if not candidate.is_absolute() and workspace is not None:+ candidate = workspace / candidate+ normalized = _safe_resolve(candidate)+ if normalized in seen:+ continue+ seen.add(normalized)+ result.append(normalized)+ return tuple(result)+++def _scan_relative_files(+ *,+ base_dir: Path,+ entries: tuple[tuple[str, str], ...],+ out: list[LoadedMemoryFile],+ seen: set[str],+ target_path: str,+ watch_paths: set[str],+) -> None:+ for rel, kind in entries:+ watch_paths.add(_safe_resolve(base_dir))+ abs_path = base_dir / rel+ if abs_path.is_file():+ _load_path(+ abs_path,+ kind,+ out,+ seen,+ target_path=target_path,+ watch_paths=watch_paths,+ )+++def _scan_relative_globs(+ *,+ base_dir: Path,+ patterns: tuple[str, ...],+ kind: str,+ out: list[LoadedMemoryFile],+ seen: set[str],+ target_path: str,+ watch_paths: set[str],+) -> None:+ for pattern in patterns:+ watch_paths.add(_safe_resolve(base_dir / Path(pattern).parent))+ for matched in sorted(_glob.glob(str(base_dir / pattern))):+ path = Path(matched)+ if path.is_file():+ _load_path(+ path,+ kind,+ out,+ seen,+ target_path=target_path,+ watch_paths=watch_paths,+ )+++def _scan_absolute_globs(+ patterns: tuple[str, ...],+ *,+ kind: str,+ out: list[LoadedMemoryFile],+ seen: set[str],+ target_path: str,+ watch_paths: set[str],+) -> None:+ for raw_pattern in patterns:+ expanded = os.path.expanduser(raw_pattern)+ watch_paths.add(_safe_resolve(Path(expanded).parent))+ for matched in sorted(_glob.glob(expanded)):+ path = Path(matched)+ if path.is_file():+ _load_path(+ path,+ kind,+ out,+ seen,+ target_path=target_path,+ watch_paths=watch_paths,+ )+++def _try_load_single(+ raw: str,+ kind: str,+ out: list[LoadedMemoryFile],+ seen: set[str],+ *,+ target_path: str,+ watch_paths: set[str],+) -> None:+ expanded = os.path.expanduser(raw)+ path = Path(expanded)+ watch_paths.add(_safe_resolve(path.parent))+ if path.is_file():+ _load_path(+ path,+ kind,+ out,+ seen,+ target_path=target_path,+ watch_paths=watch_paths,+ )+++def _load_path(+ path: Path,+ kind: str,+ out: list[LoadedMemoryFile],+ seen: set[str],+ *,+ target_path: str,+ watch_paths: set[str],+) -> None:+ try:+ resolved = str(path.resolve())+ except (OSError, ValueError, RuntimeError):+ return+ watch_paths.add(resolved)+ if resolved in seen:+ return+ seen.add(resolved)+ try:+ raw = path.read_text(encoding="utf-8", errors="replace")+ except (OSError, UnicodeError) as exc:+ logger.warning("[project_memory] failed to read %s: %s", resolved, exc)+ return++ frontmatter, body = _parse_frontmatter(raw)+ if not _frontmatter_paths_match(frontmatter, path=path, target_path=target_path):+ return++ body_without_includes = _expand_includes(+ body,+ current_path=path,+ kind=kind,+ out=out,+ seen=seen,+ target_path=target_path,+ watch_paths=watch_paths,+ )+ body_stripped = body_without_includes.strip()+ if not body_stripped:+ return+ out.append(+ LoadedMemoryFile(+ path=resolved,+ kind=kind,+ content=body_stripped,+ frontmatter=frontmatter,+ priority=PRIORITY.get(kind, 30),+ )+ )+++def _expand_includes(+ body: str,+ *,+ current_path: Path,+ kind: str,+ out: list[LoadedMemoryFile],+ seen: set[str],+ target_path: str,+ watch_paths: set[str],+) -> str:+ kept_lines: list[str] = []+ in_fence = False++ for line in body.splitlines():+ if _FENCE_RE.match(line):+ in_fence = not in_fence+ kept_lines.append(line)+ continue++ if in_fence:+ kept_lines.append(line)+ continue++ include_spec = _extract_include_spec(line)+ if include_spec is None:+ kept_lines.append(line)+ continue++ include_path = _resolve_include_path(include_spec, current_path=current_path)+ if include_path is None:+ continue+ watch_paths.add(_safe_resolve(include_path.parent))+ watch_paths.add(_safe_resolve(include_path))+ if not include_path.is_file():+ continue++ _load_path(+ include_path,+ kind,+ out,+ seen,+ target_path=target_path,+ watch_paths=watch_paths,+ )++ return "\n".join(kept_lines)+++def _extract_include_spec(line: str) -> str | None:+ stripped = line.strip()+ if not stripped:+ return None+ if stripped.startswith("@include "):+ return stripped[len("@include "):].strip()+ if stripped.startswith("@") and not stripped.startswith("@@"):+ return stripped[1:].strip()+ return None+++def _resolve_include_path(spec: str, *, current_path: Path) -> Path | None:+ cleaned = spec.strip().strip('"').strip("'")+ if not cleaned:+ return None+ if cleaned.startswith("~/"):+ return Path(os.path.expanduser(cleaned))+ if cleaned.startswith("/"):+ return Path(cleaned)+ if cleaned.startswith("./") or cleaned.startswith("../"):+ return (current_path.parent / cleaned).resolve()+ return (current_path.parent / cleaned).resolve()+++def _frontmatter_paths_match(+ frontmatter: dict,+ *,+ path: Path,+ target_path: str,+) -> bool:+ globs = _extract_paths_globs(frontmatter)+ if not globs:+ return True+ return _paths_match_target(globs, rule_path=path, target_path=target_path)+++def _extract_paths_globs(frontmatter: dict) -> tuple[str, ...]:+ raw = frontmatter.get("paths")+ if raw is None:+ return ()+ if isinstance(raw, str):+ return (raw.strip(),) if raw.strip() else ()+ if isinstance(raw, (list, tuple)):+ result = tuple(str(item).strip() for item in raw if str(item).strip())+ return result+ return ()+++def _paths_match_target(+ globs: tuple[str, ...],+ *,+ rule_path: Path,+ target_path: str,+) -> bool:+ """Match ``paths:`` globs against the current workspace/cwd path.++ This rail runs before each model call and does not have a stable notion of+ "current target file" in the surrounding business flow, so scoped rules are+ evaluated against the active workspace/cwd for the turn.+ """+ try:+ target = Path(target_path).resolve()+ project_root = find_project_root(str(target))+ if project_root is not None and not _is_relative_to(rule_path, project_root):+ rule_base = project_root+ else:+ rule_base = rule_path.parent+ for parent in rule_path.parents:+ if parent.name in {".jiuwen", ".claude"}:+ rule_base = parent.parent+ break+ relative = target.relative_to(rule_base.resolve())+ except (OSError, RuntimeError, ValueError):+ return False++ relative_posix = relative.as_posix().strip("/")+ if relative_posix:+ trail = posixpath.normpath(posixpath.join(relative_posix, ".")) + "/"+ with_dir_magic = posixpath.join(relative_posix, "__dir__")+ candidates = {relative_posix, trail, with_dir_magic}+ else:+ candidates = {"", "/", "/__dir__", ".", "__dir__"}++ for glob_pattern in globs:+ normalized = glob_pattern.strip().lstrip("./").replace("\\", "/")+ if not normalized:+ continue+ for candidate in candidates:+ if fnmatchcase(candidate, normalized):+ return True+ return False+++def _parse_frontmatter(raw: str) -> tuple[dict, str]:+ """Return ``(frontmatter_dict, body)`` using lightweight YAML parsing."""+ match = _FRONTMATTER_RE.match(raw)+ if not match:+ return {}, raw++ lines = match.group(1).splitlines()+ result: dict[str, object] = {}+ idx = 0+ while idx < len(lines):+ line = lines[idx]+ stripped = line.strip()+ if not stripped or stripped.startswith("#") or ":" not in line:+ idx += 1+ continue++ key, _, value = line.partition(":")+ key = key.strip()+ value = value.strip()+ if value:+ result[key] = _parse_frontmatter_value(value)+ idx += 1+ continue++ block: list[str] = []+ idx += 1+ while idx < len(lines):+ nxt = lines[idx]+ nxt_stripped = nxt.strip()+ if not nxt_stripped:+ idx += 1+ continue+ if not nxt.startswith((" ", "\t")) and ":" in nxt and not nxt_stripped.startswith("-"):+ break+ block.append(nxt_stripped)+ idx += 1+ result[key] = _parse_frontmatter_block(block)++ return result, raw[match.end():]+++def _parse_frontmatter_value(value: str):+ value = value.strip()+ if not value:+ return ""+ if value.startswith("[") and value.endswith("]"):+ parsed_list = _parse_inline_frontmatter_list(value)+ if parsed_list is not None:+ return parsed_list+ lowered = value.lower()+ if lowered in {"true", "false"}:+ return lowered == "true"+ if lowered in {"null", "none"}:+ return None+ return value.strip('"').strip("'")+++def _parse_inline_frontmatter_list(value: str) -> list[str] | None:+ inner = value[1:-1].strip()+ if not inner:+ return []++ items: list[str] = []+ current: list[str] = []+ quote: str | None = None+ escaped = False++ for ch in inner:+ if quote is not None:+ if escaped:+ current.append(ch)+ escaped = False+ continue+ if ch == "\\":+ escaped = True+ continue+ if ch == quote:+ quote = None+ continue+ current.append(ch)+ continue++ if ch in {'"', "'"}:+ quote = ch+ continue+ if ch == ",":+ item = "".join(current).strip()+ if item:+ items.append(item.strip('"').strip("'"))+ current = []+ continue+ current.append(ch)++ if quote is not None:+ return None++ tail = "".join(current).strip()+ if tail:+ items.append(tail.strip('"').strip("'"))+ return items+++def _parse_frontmatter_block(lines: list[str]):+ if not lines:+ return []+ if all(line.startswith("-") for line in lines):+ return [+ line[1:].strip().strip('"').strip("'")+ for line in lines+ if line[1:].strip()+ ]+ return [line.strip().strip('"').strip("'") for line in lines if line.strip()]+++def _detect_git_worktree(cwd: Path) -> GitWorktreeInfo | None:+ worktree_root = _git_path(cwd, "rev-parse", "--show-toplevel")+ common_dir = _git_path(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir")+ if worktree_root is None or common_dir is None:+ return None++ canonical_root = _canonical_root_from_common_dir(common_dir)+ if canonical_root is None:+ return None+ return GitWorktreeInfo(+ worktree_root=worktree_root,+ canonical_root=canonical_root,+ )++[email protected]_cache(maxsize=1)+def _git_executable() -> str | None:+ candidate = shutil.which("git")+ if not candidate:+ return None+ try:+ return str(Path(candidate).resolve(strict=False))+ except OSError:+ return candidate+++def _git_path(cwd: Path, *args: str) -> Path | None:+ git_exe = _git_executable()+ if git_exe is None:+ return None+ try:+ completed = subprocess.run(+ [git_exe, "-C", str(cwd), *args],+ check=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ text=True,+ timeout=2,+ )+ except (OSError, subprocess.SubprocessError, ValueError):+ return None+ output = completed.stdout.strip()+ if not output:+ return None+ try:+ return Path(output).resolve()+ except (OSError, RuntimeError, ValueError):+ return None+++def _canonical_root_from_common_dir(common_dir: Path) -> Path | None:+ if common_dir.name == ".git":+ return common_dir.parent+ parent = common_dir.parent+ if parent.name == "worktrees" and parent.parent.name == ".git":+ return parent.parent.parent+ return None+++def _should_skip_project_dir(+ directory: Path,+ worktree_info: GitWorktreeInfo | None,+) -> bool:+ if worktree_info is None:+ return False+ if worktree_info.canonical_root == worktree_info.worktree_root:+ return False+ return (+ _is_relative_to(directory, worktree_info.canonical_root)+ and not _is_relative_to(directory, worktree_info.worktree_root)+ )+++def _build_watch_snapshot(+ paths: Iterable[str],+) -> tuple[tuple[str, bool, bool, int | None, int | None], ...]:+ snapshot: list[tuple[str, bool, bool, int | None, int | None]] = []+ for raw in sorted({str(path) for path in paths if str(path).strip()}):+ path = Path(raw)+ try:+ stat_result = path.stat()+ except OSError:+ snapshot.append((raw, False, False, None, None))+ continue+ snapshot.append(+ (+ raw,+ True,+ path.is_dir(),+ getattr(stat_result, "st_mtime_ns", None),+ None if path.is_dir() else stat_result.st_size,+ )+ )+ return tuple(snapshot)+++def _is_relative_to(path: Path, root: Path) -> bool:+ try:+ path.resolve().relative_to(root.resolve())+ return True+ except (OSError, RuntimeError, ValueError):+ return False+++def _safe_resolve(path: Path) -> str:+ try:+ return str(path.resolve())+ except (OSError, RuntimeError, ValueError):+ return str(path)+++def _short(path: str) -> str:+ try:+ home = str(Path.home())+ except (OSError, RuntimeError):+ return path+ if path.startswith(home):+ return "~" + path[len(home):]+ return path+++__all__ = [+ "ADDITIONAL_DIRECTORIES_ENV",+ "DEFAULT_MAX_CHARS",+ "GitWorktreeInfo",+ "LoadedMemoryFile",+ "LOCAL_MEMORY_FILES",+ "MANAGED_MEMORY_FILES",+ "MANAGED_MEMORY_GLOBS",+ "PROJECT_MEMORY_FILES",+ "PROJECT_MEMORY_GLOBS",+ "PROJECT_ROOT_MARKERS",+ "USER_MEMORY_FILES",+ "USER_MEMORY_GLOBS",+ "clear_project_memory_cache",+ "discover_and_load_memory_files",+ "find_project_root",+ "merge_memory_content",+]diff --git a/jiuwenclaw/agentserver/deep_agent/rails/project_memory/section.py b/jiuwenclaw/agentserver/deep_agent/rails/project_memory/section.pynew file mode 100644index 0000000000..f610dcd426--- /dev/null+++ b/jiuwenclaw/agentserver/deep_agent/rails/project_memory/section.py@@ -0,0 +1,54 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""PromptSection factory for project memory."""+from __future__ import annotations++from typing import Optional++from openjiuwen.harness.prompts import PromptSection++# Section name used by both the factory and the Rail to add/remove.+# Using a string literal (not ``SectionName.*``) so we don't need to+# modify agent-core's ``SectionName`` enum.+SECTION_NAME = "project_memory"++_HEADER_CN = "## 项目记忆(ProjectMemoryRail 自动加载)"+_HEADER_EN = "## Project Memory (auto-loaded by ProjectMemoryRail)"++_NOTE_CN = (+ "以下内容来自项目根、用户目录、本地私有文件的合并。"+ "修改磁盘文件即可在下一轮对话生效。"+)+_NOTE_EN = (+ "The following is merged from project root, user home, and local private files. "+ "Edits take effect on the next turn."+)+++def build_project_memory_section(+ content: str,+ *,+ language: str = "cn", # kept for backward compat; both languages are always populated+ priority: int = 120,+) -> Optional[PromptSection]:+ """Build the ``project_memory`` :class:`PromptSection`, or ``None`` when content is empty.++ Both ``cn`` and ``en`` content keys are always populated so that whichever+ language the agent renders with, the header/note prose stays in the right+ language. The ``language`` parameter is kept for API stability but no longer+ affects which keys are included.+ """+ del language # accepted for API compat, not used.+ if not content or not content.strip():+ return None+ body_text = content.strip()+ body_cn = f"{_HEADER_CN}\n\n{_NOTE_CN}\n\n{body_text}\n"+ body_en = f"{_HEADER_EN}\n\n{_NOTE_EN}\n\n{body_text}\n"+ return PromptSection(+ name=SECTION_NAME,+ content={"cn": body_cn, "en": body_en},+ priority=priority,+ )+++__all__ = ["build_project_memory_section", "SECTION_NAME"]diff --git a/jiuwenclaw/agentserver/deep_agent/rails/project_memory_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/project_memory_rail.pynew file mode 100644index 0000000000..589b2a16f6--- /dev/null+++ b/jiuwenclaw/agentserver/deep_agent/rails/project_memory_rail.py@@ -0,0 +1,221 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""ProjectMemoryRail -- jiuwenclaw product-side rail.++On every ``before_model_call``, rebuild the ``project_memory`` section from+cached discovery results. Cache invalidation happens explicitly on write-like+tool calls, mode/workspace switches, and also falls back to a lightweight+filesystem snapshot check for correctness.++This rail lives in jiuwenclaw (not agent-core) so that:++* agent-core stays untouched+* jiuwenclaw can evolve memory-loading semantics without upstream PRs+"""+from __future__ import annotations++import os+from typing import TYPE_CHECKING++from openjiuwen.core.single_agent.rail.base import AgentCallbackContext+from openjiuwen.harness.rails.base import DeepAgentRail++from jiuwenclaw.agentserver.deep_agent.rails.project_memory import (+ SECTION_NAME,+ build_project_memory_section,+ clear_project_memory_cache,+ discover_and_load_memory_files,+ merge_memory_content,+)+from jiuwenclaw.utils import logger++if TYPE_CHECKING:+ from openjiuwen.harness.deep_agent import DeepAgent+++class ProjectMemoryRail(DeepAgentRail):+ """Auto-load project memory files and inject them into the system prompt.++ Loaded sources (all read-only; only ``JIUWENCLAW.md`` and+ ``JIUWENCLAW.local.md`` are written by ``/init``):++ * **Project root**: ``JIUWENCLAW.md``, ``JIUWENCLAW.local.md``,+ ``.jiuwen/JIUWENCLAW.md``, ``.jiuwen/rules/*.md``+ * **User level**: ``~/.jiuwen/JIUWENCLAW.md``, ``~/.jiuwen/rules/*.md``+ * **Managed**: ``/etc/jiuwen/JIUWENCLAW.md``, ``/etc/jiuwen/rules/*.md``+ * **Additional dirs**: explicit project-memory directories passed to the rail++ Priority (low -> high): ``managed < user < project (root -> cwd) < local``.+ """++ WRITE_LIKE_TOOLS = frozenset({+ "write_file",+ "edit_file",+ "write_text_file",+ "write",+ "delete_file",+ "delete",+ "move_file",+ "rename_file",+ })++ # Higher than MEMORY(85) / TOOLS(~100); lower than RUNTIME (see+ # agent-core ``prompts/sections/__init__.py`` SectionName for the+ # conventional range).+ SECTION_PRIORITY = 120++ def __init__(+ self,+ workspace: str,+ *,+ language: str = "cn",+ max_chars: int = 60_000,+ additional_directories: tuple[str, ...] | None = None,+ ) -> None:+ super().__init__()+ # NOTE: 父类 DeepAgentRail.set_workspace() 会把 self.workspace 替换成+ # Workspace 对象(DeepAgent.register_rail 内部强制注入)。这里改用+ # 私有属性 _workspace_path 保存构造期传入的字符串路径,避免被覆盖。+ self._workspace_path: str = workspace+ self._language: str = language+ self._max_chars: int = max_chars+ self._additional_directories: tuple[str, ...] = tuple(additional_directories or ())+ self._system_prompt_builder = None++ # ------------------------------------------------------------------+ # Lifecycle+ # ------------------------------------------------------------------++ def init(self, agent: "DeepAgent") -> None:+ self._system_prompt_builder = getattr(agent, "system_prompt_builder", None)+ if self._system_prompt_builder is None:+ logger.warning(+ "[ProjectMemoryRail] agent has no system_prompt_builder; disabled"+ )+ return+ logger.info(+ "[ProjectMemoryRail] initialized for workspace=%s language=%s",+ self.resolve_workspace_path(),+ self._language,+ )++ def uninit(self, agent: "DeepAgent") -> None:+ """Clear the injected section to avoid stale content on rail swap."""+ clear_project_memory_cache(self.resolve_workspace_path())+ if self._system_prompt_builder is not None:+ try:+ self._system_prompt_builder.remove_section(SECTION_NAME)+ except Exception as exc: # noqa: BLE001 -- defensive; never crash teardown+ logger.warning(+ "[ProjectMemoryRail] remove_section on uninit failed: %s", exc+ )++ # ------------------------------------------------------------------+ # Public knobs (per-request hot updates, parallel to RuntimePromptRail)+ # ------------------------------------------------------------------++ def set_language(self, language: str) -> None:+ """Per-request language switch (cn/en). No-op if value unchanged."""+ if language and language != self._language:+ self._language = language++ def get_language(self) -> str:+ """Get current language setting."""+ return self._language++ def set_additional_directories(self, dirs: tuple[str, ...] | list[str] | None) -> None:+ """Per-request hot update of additional scan directories.++ Called by the adapter when ``trusted_dirs`` arrives from the client,+ ensuring the rail always searches the directory where /init wrote+ JIUWENCLAW.md (typically the CLI process's cwd, which differs from+ the AgentServer process cwd).+ """+ extra = tuple(dirs or ())+ # Merge with constructor-level dirs, dedup by realpath+ base_resolved = {os.path.realpath(d) for d in self._additional_directories}+ merged = list(self._additional_directories)+ for d in extra:+ if os.path.realpath(d) not in base_resolved:+ merged.append(d)+ base_resolved.add(os.path.realpath(d))+ self._additional_directories = tuple(merged)++ # ------------------------------------------------------------------+ # Hook+ # ------------------------------------------------------------------++ async def before_model_call(self, ctx: AgentCallbackContext) -> None: # noqa: ARG002+ """Refresh the ``project_memory`` section from cached discovery state."""+ if self._system_prompt_builder is None:+ return++ workspace_path = self.resolve_workspace_path()++ try:+ # ``paths:`` scoped rules are evaluated against the active workspace/cwd+ # for this turn. The surrounding DeepAgent callback does not provide a+ # stable "current target file" concept here.+ files = discover_and_load_memory_files(+ workspace=workspace_path,+ target_path=workspace_path,+ additional_directories=self._additional_directories,+ )+ except (OSError, ValueError, TypeError) as exc:+ # 不能让 rail 崩坏 model call;但要把根因留在日志里,方便排查。+ logger.exception(+ "[ProjectMemoryRail] discovery failed for workspace=%s: %s",+ workspace_path,+ exc,+ )+ files = []++ merged = merge_memory_content(files, max_chars=self._max_chars)++ # Always drop the previous section so the current state of disk wins.+ try:+ self._system_prompt_builder.remove_section(SECTION_NAME)+ except Exception as exc: # noqa: BLE001 -- builder API surface is broad+ logger.warning(+ "[ProjectMemoryRail] remove_section failed (continuing): %s", exc+ )++ if not merged.strip():+ return++ section = build_project_memory_section(+ merged,+ language=self._language,+ priority=self.SECTION_PRIORITY,+ )+ if section is not None:+ self._system_prompt_builder.add_section(section)++ async def after_tool_call(self, ctx: AgentCallbackContext) -> None:+ """Explicitly invalidate memory discovery cache after write-like tools."""+ tool_name = str(getattr(ctx.inputs, "tool_name", "") or "").strip()+ if tool_name not in self.WRITE_LIKE_TOOLS:+ return+ clear_project_memory_cache(self.resolve_workspace_path())++ # ------------------------------------------------------------------+ # Internal+ # ------------------------------------------------------------------++ def resolve_workspace_path(self) -> str:+ """Resolve the workspace root as a string path.++ Order of precedence:+ 1. ``self.workspace.root_path`` -- injected by ``DeepAgent.register_rail``+ via ``DeepAgentRail.set_workspace(Workspace(...))``. Most up-to-date.+ 2. ``self._workspace_path`` -- string path passed at construction.+ """+ ws_obj = getattr(self, "workspace", None)+ if ws_obj is not None:+ root = getattr(ws_obj, "root_path", None)+ if root:+ return str(root)+ return self._workspace_path+++__all__ = ["ProjectMemoryRail"]diff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.tsindex 2ddd78cdd3..8720dbdca8 100644--- a/jiuwenclaw/cli/src/app-state.ts+++ b/jiuwenclaw/cli/src/app-state.ts@@ -417,6 +417,7 @@ export class CliPiAppState {setTrustedDir: setTrustedDir,removeTrustedDir: removeTrustedDir,clearTrustedDirs: clearTrustedDirs,+ getWorkspaceDir: () => process.cwd(),enterConfigEditor: undefined, // AppScreen injects the real handler when executing slash commands.};}@@ -597,6 +598,7 @@ readonly request = async <T = Record<string, unknown>>(content: string,attachments?: FileAttachment[],modeOverride?: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "team",+ options?: { logAsUser?: boolean },): string | null => {if (this.connectionStatus !== "connected") return null;const mode = modeOverride ?? this.mode;@@ -610,16 +612,18 @@ readonly request = async <T = Record<string, unknown>>(...(attachments?.length ? { attachments } : {}),});this.lastError = null;- this.entries = [- ...this.entries,- {- kind: "user",- id: `user-${requestId}`,- sessionId: this.sessionId,- content,- at: new Date().toISOString(),- },- ];+ if (options?.logAsUser !== false) {+ this.entries = [+ ...this.entries,+ {+ kind: "user",+ id: `user-${requestId}`,+ sessionId: this.sessionId,+ content,+ at: new Date().toISOString(),+ },+ ];+ }this.streamingState = StreamingState.Responding;this.emitChange();return requestId;diff --git a/jiuwenclaw/cli/src/core/commands/builtins/init.prompts.ts b/jiuwenclaw/cli/src/core/commands/builtins/init.prompts.tsnew file mode 100644index 0000000000..088ae01d38--- /dev/null+++ b/jiuwenclaw/cli/src/core/commands/builtins/init.prompts.ts@@ -0,0 +1,404 @@+import type { CommandContext } from "../types.js";++export type ScopeKey = "project" | "personal" | "both";++export interface ExistingFiles {+ jiuwenclawMd: boolean;+ jiuwenclawLocalMd: boolean;+ claudeMd: boolean;+ claudeLocalMd: boolean;+ agentsMd: boolean;+ openjiuwenMd: boolean;+ cursorRules: boolean;+ copilotInstructions: boolean;+}++export interface BuildInitPromptArgs {+ rootDir: string;+ scopeKey: ScopeKey;+ language: "zh" | "en";+ existing: ExistingFiles;+}++// ---------------------------------------------------------------------------+// Language resolution+// ---------------------------------------------------------------------------++export function resolveLanguage(_ctx: CommandContext): "zh" | "en" {+ // 当前方案:best-effort from LANG env; 后续可读 config.+ const lang =+ typeof process !== "undefined" ? (process.env.LANG ?? "") : "";+ return /^zh/i.test(lang) || /CN$/i.test(lang) ? "zh" : "en";+}++// ---------------------------------------------------------------------------+// Prompt builder+// ---------------------------------------------------------------------------++export function buildInitPrompt(args: BuildInitPromptArgs): string {+ return args.language === "zh" ? buildInitPromptZh(args) : buildInitPromptEn(args);+}++// ---------------------------------------------------------------------------+// English (authoritative source)+// ---------------------------------------------------------------------------++function buildInitPromptEn({ rootDir, scopeKey, existing }: BuildInitPromptArgs): string {+ const scopeLine = SCOPE_DESCRIPTION_EN[scopeKey];+ return `Set up a minimal JIUWENCLAW.md (team-shared) and optionally JIUWENCLAW.local.md (personal) for this repository.++These files are auto-loaded into every coding-mode session by ProjectMemoryRail, so they must be CONCISE — only include what the assistant would get wrong without them.++## CRITICAL Constraints (read first, do not violate)++1. **All file operations MUST use absolute paths rooted at: \`${rootDir}\`**+ Never use relative paths. When writing or editing, always construct \`${rootDir}/<filename>\`.+2. **Do NOT use the \`coding_memory_read\` / \`coding_memory_write\` / \`coding_memory_edit\` tools in this command.** Those are for session-level auto-memory, a different system. /init produces static project documents via the file write tools only.+3. **Existing files pre-detected in workspace root**:+ - JIUWENCLAW.md: ${yesNo(existing.jiuwenclawMd)} ${existing.jiuwenclawMd ? "— you MUST read it first, propose a diff, then use \`ask_user\` tool to ask the user whether to apply. Offer options: \"Apply update\" / \"Skip (keep current)\". If user chooses apply, use Edit to apply the diff; if skip, leave the file unchanged and continue. NEVER silently overwrite." : ""}+ - JIUWENCLAW.local.md: ${yesNo(existing.jiuwenclawLocalMd)} ${existing.jiuwenclawLocalMd ? "— propose additions via Edit only, never overwrite." : ""}+ - Legacy reference files (do NOT delete or rewrite; you may link to them): CLAUDE.md=${yesNo(existing.claudeMd)}, CLAUDE.local.md=${yesNo(existing.claudeLocalMd)}, AGENTS.md=${yesNo(existing.agentsMd)}, OPENJIUWEN.md=${yesNo(existing.openjiuwenMd)}, .cursorrules=${yesNo(existing.cursorRules)}, .github/copilot-instructions.md=${yesNo(existing.copilotInstructions)}+4. **When the explore sub-agent runs bash commands**, always prefix with \`cd ${rootDir} && ...\` or use \`git -C ${rootDir}\` — sub-agent CWD is not guaranteed to equal \`${rootDir}\`.+5. **Always prefer \`task_tool\` with \`subagent_type: "explore_agent"\` when it is available.** If \`task_tool\` is unavailable for this turn, silently FALL BACK to \`glob\` / \`grep\` / \`read_file\` / \`bash\` yourself.+6. **Default to a single \`task_tool\` / \`explore_agent\` call.** If the repository is clearly large, a monorepo, or one pass does not gather enough signal, you may split the work across multiple explore sub-agents; only parallelize when there is a clear benefit, to avoid duplicate scanning and noisy result merging.++## Step 1: Scope (already answered)++User chose: **${scopeKey}** — ${scopeLine}++## Step 2: Explore the codebase++Preferred path — invoke \`task_tool\` with:+\`\`\`+subagent_type: "explore_agent"+task_description: |+ Thoroughly explore the repository at ${rootDir}. Use "very thorough" exploration.+ Read these key files if present (use absolute paths):+ - Manifests: package.json, Cargo.toml, pyproject.toml, go.mod, pom.xml, build.gradle*, setup.py+ - Docs: README.*, CONTRIBUTING.*, ARCHITECTURE.*, docs/+ - Build/CI: Makefile, justfile, .github/workflows/*, .gitlab-ci.yml, azure-pipelines.yml+ - AI tool configs: JIUWENCLAW.md, CLAUDE.md, AGENTS.md, OPENJIUWEN.md,+ .jiuwen/rules/*, .claude/rules/*, .cursor/rules/*,+ .cursorrules, .github/copilot-instructions.md,+ .windsurfrules, .clinerules, .mcp.json+ - Config: .jiuwen/settings*.json (read-only; do not rewrite)+ Detect and report back concisely:+ - Build / test / lint / format commands (especially non-standard ones)+ - Primary languages, frameworks, package manager+ - Project structure (monorepo, multi-module, single-package)+ - Code style rules differing from language defaults+ - Non-obvious gotchas, required env vars, workflow quirks+ - Branch / PR / commit message conventions+ - Run \`git -C ${rootDir} worktree list\` and mention if multiple worktrees exist+ Note anything you CANNOT figure out from code alone — these become interview questions.+\`\`\`++Fallback (no task_tool): do the same yourself with \`glob\` and \`read_file\`; focus on the manifest + README first, then Makefile / CI configs.++## Step 3: Fill gaps + build proposal++Gather info code can't answer. Preferred: use the \`ask_user\` tool.+- If \`ask_user\` supports \`questions: [...]\` multi-choice schema, use it.+- Otherwise, write the questions as plain text in your reply and wait for the user's next turn.++For scope \`project\` / \`both\`: ask about team practices —+ non-obvious commands, branch/PR conventions, env setup, testing quirks, common pitfalls.+ Skip items already obvious from README or manifests. Do not mark any answer as "recommended" — this is about the team's actual workflow.++For scope \`personal\` / \`both\`: ask about the user —+ role, familiarity with this codebase, sandbox URLs / accounts, communication preferences, specific tooling setup on their machine.++**Synthesize a proposal** combining Step 2 findings and Step 3 answers. Because skills and hooks are outside the current scope, ALL items become JIUWENCLAW.md notes (team) or JIUWENCLAW.local.md notes (personal). Present as a plain-text list, one line per item, grouped by target file. Ask for confirmation before proceeding.++**Build the preference queue** from the accepted proposal:+\`[{type: "note", target: "JIUWENCLAW.md" | "JIUWENCLAW.local.md", content: "..."}]\`+Steps 4–5 consume this queue.++## Step 4: Write JIUWENCLAW.md (if scope is project or both)++Target: \`${rootDir}/JIUWENCLAW.md\`++${existing.jiuwenclawMd ? "File EXISTS — read it, propose a merged diff, WAIT for user confirmation, then apply via Edit. DO NOT use Write to overwrite silently." : "File is absent — use Write to create it."}++Consume queue entries whose \`target == "JIUWENCLAW.md"\`.++**Content test**: for each candidate line, ask "Would removing this cause the assistant to make mistakes?" If no, cut.++**Include**:+- Build / test / lint / format commands the assistant can't guess+- Code style rules that deviate from language defaults+- Testing quirks (e.g., "run single test with \`pytest -k ...\`")+- Repo etiquette (branch naming, PR conventions, commit message style)+- Required env vars, setup steps+- Important parts from existing AI coding tool configs if they exist (AGENTS.md, .cursor/rules, .cursorrules, .github/copilot-instructions.md, .windsurfrules, .clinerules) — extract key rules, not just link to them+- Non-obvious gotchas, architectural decisions worth knowing+- A brief **See also** section. Use plain markdown links for short references, or \`@path/to/file\` includes when a longer source document should stay authoritative:+ ${legacyIncludesEn(existing)}++**Exclude**:+- File-by-file structure or component lists (assistant can discover)+- Standard language conventions (assistant already knows)+- Generic AI etiquette / prompt engineering advice+- Long inline reference material — link to it rather than inline+- Commands already obvious from manifests (e.g., "npm test")+- Frequently-changing information — reference the source with \`@path/to/doc.md\` so the latest version is always loaded+- Generic advice like "write clean code" or "handle errors" — only include specific, actionable rules++**Specificity rule**: "Use 2-space indentation in TypeScript" is better than "Format code properly."++**No invented sections**: Do not make up headings like "Common Development Tasks" or "Tips for Development" — only include information expressly found in files you read.++**Prefix** the file with:+\`\`\`+# JIUWENCLAW.md++This file provides guidance to JiuwenClaw (and any compatible AI coding assistant) when working with code in this repository.+\`\`\`++For monorepos: mention that subdirectory \`JIUWENCLAW.md\` is supported — ProjectMemoryRail walks up from cwd, so per-package docs are welcome.++For rule organization at team scale: suggest creating \`.jiuwen/rules/<topic>.md\` — these are auto-scanned, and may use frontmatter \`paths:\` to scope rules by the current working subtree / workspace.++## Step 5: Write JIUWENCLAW.local.md (if scope is personal or both)++Target: \`${rootDir}/JIUWENCLAW.local.md\`++${existing.jiuwenclawLocalMd ? "File EXISTS — propose additions via Edit, never overwrite." : "File is absent — use Write to create it."}++Consume queue entries whose \`target == "JIUWENCLAW.local.md"\`.++Include: user's role, familiarity, personal URLs / accounts, communication preferences, tool setup specific to the user's machine.++**After writing**, idempotently update \`${rootDir}/.gitignore\`:+ 1. Read \`.gitignore\` if it exists (use absolute path).+ 2. Check whether each of the two lines below is already present (exact line match).+ 3. Append only the missing ones:+ - \`JIUWENCLAW.local.md\`+ - \`.jiuwen/settings.local.json\`+ 4. If \`.gitignore\` does not exist, create it with those two lines.++## Step 6: Summary++Briefly recap which files were written and the 3–5 most important items in each.++Remind the user:+- These files are auto-loaded into every coding session by ProjectMemoryRail.+- They're a starting point — feel free to edit by hand; changes take effect next turn.+- Re-run \`/init\` anytime to refresh based on new findings.++Then suggest optimizations as a short checklist, only those relevant to this repo:+- If tests are missing / sparse: suggest setting up a framework so the assistant can verify its own changes.+- If no formatter / lint config was found: suggest adding one with a one-line reason.+- If Step 2 found legacy AI config files (CLAUDE.md, AGENTS.md, etc.) not referenced in JIUWENCLAW.md: suggest consolidating via plain links or follow-up cleanup.+- **Always include**: "Run \`/compact\` after reviewing to trim this init session from history."+`;+}++// ---------------------------------------------------------------------------+// Chinese+// ---------------------------------------------------------------------------++function buildInitPromptZh({ rootDir, scopeKey, existing }: BuildInitPromptArgs): string {+ const scopeLine = SCOPE_DESCRIPTION_ZH[scopeKey];+ return `为本仓库生成一份最小可用的 JIUWENCLAW.md(团队共享)与可选的 JIUWENCLAW.local.md(个人私有)。+这些文件会被 ProjectMemoryRail 自动注入到每一轮 coding 模式会话的 system prompt,因此必须**精简** —— 只写"不写就会出错"的信息。++## 关键约束(必读,不可违反)++1. **所有文件操作必须使用绝对路径,根为:\`${rootDir}\`**+ 永远不要用相对路径。写入或编辑时总是构造 \`${rootDir}/<文件名>\`。+2. **禁止使用 \`coding_memory_read\` / \`coding_memory_write\` / \`coding_memory_edit\` 工具。** 那是会话级自动记忆,和 /init 是两套系统。/init 只通过文件写入工具产出静态项目文档。+3. **工作区根目录现有文件(已预探测)**:+ - JIUWENCLAW.md:${yesNoZh(existing.jiuwenclawMd)} ${existing.jiuwenclawMd ? "—— 必须先读取、生成 diff,然后用 \`ask_user\` 工具询问用户是否应用更新。提供选项:「应用更新」 / 「跳过(保留当前)」。若用户选应用,用 Edit 执行 diff;若选跳过,保持文件不变继续后续步骤。严禁静默覆盖。" : ""}+ - JIUWENCLAW.local.md:${yesNoZh(existing.jiuwenclawLocalMd)} ${existing.jiuwenclawLocalMd ? "— 只能通过 Edit 追加,不要覆盖。" : ""}+ - 遗留参考文件(不要删改,可用 markdown 链接引用):CLAUDE.md=${yesNoZh(existing.claudeMd)}, CLAUDE.local.md=${yesNoZh(existing.claudeLocalMd)}, AGENTS.md=${yesNoZh(existing.agentsMd)}, OPENJIUWEN.md=${yesNoZh(existing.openjiuwenMd)}, .cursorrules=${yesNoZh(existing.cursorRules)}, .github/copilot-instructions.md=${yesNoZh(existing.copilotInstructions)}+4. **子代理 bash 命令必须加前缀**:\`cd ${rootDir} && ...\` 或用 \`git -C ${rootDir}\`,因为子代理的 CWD 不保证等于 \`${rootDir}\`。+5. **只要可用,始终优先使用 \`task_tool\` 且 \`subagent_type: "explore_agent"\`。** 若本轮工具列表里没有 \`task_tool\`,就静默降级为用 \`glob\` / \`grep\` / \`read_file\` / \`bash\` 自行探索。+6. **默认只发起一次 \`task_tool\` / \`explore_agent\` 调用。** 若仓库明显较大、为 monorepo,或单次探索信息不足,可按需拆分多个 explore 子代理;只有在确有收益时才并发,避免重复扫描与结果合并噪音。++## 步骤 1:范围(已确定)++用户选择:**${scopeKey}** — ${scopeLine}++## 步骤 2:探索代码库++首选:调用 \`task_tool\`,参数:+\`\`\`+subagent_type: "explore_agent"+task_description: |+ 彻底探索仓库 ${rootDir},请求 "very thorough" 级别。+ 若存在请读取(用绝对路径):+ - 清单:package.json, Cargo.toml, pyproject.toml, go.mod, pom.xml, build.gradle*, setup.py+ - 文档:README.*, CONTRIBUTING.*, ARCHITECTURE.*, docs/+ - 构建/CI:Makefile, justfile, .github/workflows/*, .gitlab-ci.yml, azure-pipelines.yml+ - AI 配置:JIUWENCLAW.md, CLAUDE.md, AGENTS.md, OPENJIUWEN.md,+ .jiuwen/rules/*, .claude/rules/*, .cursor/rules/*,+ .cursorrules, .github/copilot-instructions.md,+ .windsurfrules, .clinerules, .mcp.json+ - 配置:.jiuwen/settings*.json(只读,不要重写)+ 简洁地汇报以下内容:+ - 构建/测试/lint/format 命令(特别是非标准的)+ - 主要语言、框架、包管理器+ - 项目结构(monorepo / 多模块 / 单包)+ - 与语言默认不同的代码风格规则+ - 不易察觉的坑、必需环境变量、工作流习惯+ - 分支 / PR / commit message 约定+ - 执行 \`git -C ${rootDir} worktree list\`,若有多 worktree 请说明+ 对于从代码无法推断的问题,记录下来作为后续的访谈问题。+\`\`\`++无 task_tool 时的兜底:用 \`glob\` + \`read_file\` 自己做同样的事,先看清单和 README,再看 Makefile / CI 配置。++## 步骤 3:补齐信息 + 生成提案++收集代码无法回答的问题。优先用 \`ask_user\` 工具:+- 若 \`ask_user\` 支持 \`questions: [...]\` 多选 schema,就用它;+- 否则把问题写进你的回复里,等用户下一轮回答。++对 \`project\` / \`both\` 范围:询问团队实践 —+ 非显而易见的命令、分支 / PR 约定、环境初始化、测试习惯、常见坑位。+ README 或清单里已经写清楚的就别问。**不要**给任何选项标记"推荐" —— 这是团队实际做法,不是建议。++对 \`personal\` / \`both\` 范围:询问用户 —+ 角色、对本仓库的熟悉度、沙箱 URL / 账号、沟通偏好、本机工具链特殊设置。++**合成提案**:把步骤 2 的发现和步骤 3 的回答整合。当前方案不支持 Skills 和 Hooks,所有条目一律归为 JIUWENCLAW.md(团队)或 JIUWENCLAW.local.md(个人)的记录项。用纯文本列表呈现,按目标文件分组。请求用户确认后再写文件。++**构造偏好队列**:+\`[{type: "note", target: "JIUWENCLAW.md" | "JIUWENCLAW.local.md", content: "..."}]\`+后续写文件步骤会消费此队列。++## 步骤 4:写 JIUWENCLAW.md(当范围是 project 或 both)++目标:\`${rootDir}/JIUWENCLAW.md\`++${existing.jiuwenclawMd ? "文件已存在 —— 先读取,生成合并 diff,等用户确认,然后用 Edit 应用。绝不要用 Write 静默覆盖。" : "文件不存在 —— 用 Write 创建。"}++消费队列中 \`target == "JIUWENCLAW.md"\` 的条目。++**内容筛选测试**:对每行候选,自问"去掉这行会不会让助手犯错?" 不会就删掉。++**应包含**:+- 助手猜不出的构建 / 测试 / lint / format 命令+- 偏离语言默认的代码风格规则+- 测试习惯(例如"用 \`pytest -k 'x'\` 跑单测")+- 仓库规矩(分支命名、PR 约定、commit message 风格)+- 必需环境变量、初始化步骤+- 从已有的 AI 工具配置文件中提取重要内容(CLAUDE.md、AGENTS.md、.cursorrules、.github/copilot-instructions.md、.windsurfrules、.clinerules 等) —— 提取关键规则,而非只留链接引用+- 不易察觉的坑、值得知道的架构决策+- 简短的 **See also** 段落。短引用可用普通 markdown 链接;若希望保留长文档作为权威来源,可用 \`@path/to/file\` 引用:+ ${legacyIncludesZh(existing)}++**不应包含**:+- 逐文件 / 逐组件的结构清单(助手可以自己发现)+- 语言的标准约定(助手已经知道)+- 通用 AI 礼仪 / prompt 工程建议+- 长篇参考材料 —— 用链接引用而非内联+- 清单中显而易见的命令(比如"npm test")+- 频繁变化的信息 —— 用 \`@path/to/doc.md\` 引用源头,确保每次加载的都是最新版本+- 通用建议如"写干净代码"或"处理好错误" —— 只写具体、可执行的规则++**具体性原则**:"TypeScript 用 2 空格缩进"比"代码要格式规范"好。++**禁止虚构段落**:不要自创"常见开发任务"或"开发技巧"之类的标题 —— 只收录你从文件中实际读到的信息。++**文件开头**统一加:+\`\`\`+# JIUWENCLAW.md++This file provides guidance to JiuwenClaw (and any compatible AI coding assistant) when working with code in this repository.+\`\`\`++对 monorepo:说明支持子目录放独立的 \`JIUWENCLAW.md\` —— ProjectMemoryRail 从 cwd 向上遍历加载。++对团队规模较大的项目:建议把按主题拆分的规则放到 \`.jiuwen/rules/<topic>.md\` —— 当前运行时会自动加载这些规则,并支持用 \`paths:\` frontmatter 按当前工作目录 / workspace 所在子树限定作用域。++## 步骤 5:写 JIUWENCLAW.local.md(当范围是 personal 或 both)++目标:\`${rootDir}/JIUWENCLAW.local.md\`++${existing.jiuwenclawLocalMd ? "文件已存在 —— 通过 Edit 追加内容,不要覆盖。" : "文件不存在 —— 用 Write 创建。"}++消费队列中 \`target == "JIUWENCLAW.local.md"\` 的条目。++包含:用户的角色、对仓库的熟悉程度、个人 URL / 账号、沟通偏好、本机特有工具链配置。++**写完后幂等更新** \`${rootDir}/.gitignore\`:+ 1. 若 \`.gitignore\` 存在先读取(用绝对路径);+ 2. 检查下面两行是否已存在(整行精确匹配);+ 3. 仅追加缺失的:+ - \`JIUWENCLAW.local.md\`+ - \`.jiuwen/settings.local.json\`+ 4. 若 \`.gitignore\` 不存在,就创建并写入这两行。++## 步骤 6:总结++简要回顾写了哪些文件,每个文件里 3-5 条最重要的内容。++提醒用户:+- 这些文件会被 ProjectMemoryRail 自动加载到每一轮 coding 会话。+- 是起点 —— 可以手工编辑,下一轮就生效。+- 随时可以再跑 \`/init\` 基于新发现重新生成。++然后给一个短清单(只写与当前仓库相关的):+- 若测试缺失 / 稀疏:建议引入测试框架,助手才能自证修改。+- 若没有 formatter / lint 配置:建议添加,并说明一行理由。+- 若步骤 2 发现了 JIUWENCLAW.md 中未引用的遗留 AI 配置文件(CLAUDE.md、AGENTS.md 等):建议以普通链接方式提示用户后续合并。+- **总是包含**:"检查完后运行 \`/compact\` 可把这段初始化会话从历史中精简掉。"+`;+}++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++const SCOPE_DESCRIPTION_EN: Record<ScopeKey, string> = {+ project: "write only JIUWENCLAW.md (run Step 4).",+ personal: "write only JIUWENCLAW.local.md (run Step 5).",+ both: "write both files (run Step 4 and Step 5).",+};++const SCOPE_DESCRIPTION_ZH: Record<ScopeKey, string> = {+ project: "只写 JIUWENCLAW.md(执行步骤 4)。",+ personal: "只写 JIUWENCLAW.local.md(执行步骤 5)。",+ both: "两份都写(步骤 4 和步骤 5 都执行)。",+};++function yesNo(b: boolean): string {+ return b ? "EXISTS" : "absent";+}++function yesNoZh(b: boolean): string {+ return b ? "存在" : "不存在";+}++function legacyIncludesEn(existing: ExistingFiles): string {+ // 当前方案:不用 @path 展开;写普通 markdown 链接+ const parts: string[] = [];+ if (existing.claudeMd) parts.push("[CLAUDE.md](./CLAUDE.md)");+ if (existing.agentsMd) parts.push("[AGENTS.md](./AGENTS.md)");+ if (existing.openjiuwenMd) parts.push("[OPENJIUWEN.md](./OPENJIUWEN.md)");+ if (existing.cursorRules) parts.push("[.cursorrules](./.cursorrules)");+ if (existing.copilotInstructions)+ parts.push(+ "[.github/copilot-instructions.md](./.github/copilot-instructions.md)",+ );+ return parts.length+ ? `"See also: ${parts.join(", ")}."`+ : `"(No legacy AI config files detected.)"`;+}++function legacyIncludesZh(existing: ExistingFiles): string {+ const parts: string[] = [];+ if (existing.claudeMd) parts.push("[CLAUDE.md](./CLAUDE.md)");+ if (existing.agentsMd) parts.push("[AGENTS.md](./AGENTS.md)");+ if (existing.openjiuwenMd) parts.push("[OPENJIUWEN.md](./OPENJIUWEN.md)");+ if (existing.cursorRules) parts.push("[.cursorrules](./.cursorrules)");+ if (existing.copilotInstructions)+ parts.push(+ "[.github/copilot-instructions.md](./.github/copilot-instructions.md)",+ );+ return parts.length+ ? `"另见:${parts.join("、")}。"`+ : `"(未探测到遗留 AI 配置文件。)"`;+}diff --git a/jiuwenclaw/cli/src/core/commands/builtins/init.ts b/jiuwenclaw/cli/src/core/commands/builtins/init.tsindex 97f0fe8ded..69f85cdd12 100644--- a/jiuwenclaw/cli/src/core/commands/builtins/init.ts+++ b/jiuwenclaw/cli/src/core/commands/builtins/init.ts@@ -1,272 +1,226 @@+import { existsSync } from "node:fs";+import { join } from "node:path";+import { addError, addInfo } from "../helpers.js";import { CommandKind, type SlashCommand } from "../types.js";-import type { UserAnswer } from "../../event-handlers.js";--type InitModelConfig = {- model_provider: string;- model: string;- api_base: string;- api_key: string;-};+import {+ buildInitPrompt,+ resolveLanguage,+ type ExistingFiles,+ type ScopeKey,+} from "./init.prompts.js";++// ---------------------------------------------------------------------------+// Scope options (labels are UI-only; ScopeKey is the internal identifier).+// ---------------------------------------------------------------------------++interface ScopeOption {+ key: ScopeKey;+ label: string;+ description: string;+}-type StoredConfigPayload = Partial<InitModelConfig> & {- api_key_set?: boolean;-};+function getScopeOptions(lang: "zh" | "en"): ScopeOption[] {+ if (lang === "zh") {+ return [+ {+ key: "project",+ label: "团队共享 (JIUWENCLAW.md)",+ description:+ "签入版本库,供团队共用 —— 架构说明、编码规范、常用命令、CI 约定等。",+ },+ {+ key: "personal",+ label: "个人私有 (JIUWENCLAW.local.md)",+ description:+ "只属于你自己,加入 .gitignore —— 个人偏好、沙箱地址、私有凭据、工作习惯。",+ },+ {+ key: "both",+ label: "都要 (团队 + 个人)",+ description: "同时写两份文件。",+ },+ ];+ }+ return [+ {+ key: "project",+ label: "Team-shared (JIUWENCLAW.md)",+ description:+ "Checked into source control — architecture, coding standards, common commands, CI conventions.",+ },+ {+ key: "personal",+ label: "Personal (JIUWENCLAW.local.md)",+ description:+ "Private to you, gitignored — preferences, sandbox URLs, credentials, workflow quirks.",+ },+ {+ key: "both",+ label: "Both (team + personal)",+ description: "Write both files.",+ },+ ];+}-type ValidateModelPayload = {- provider?: string;- model?: string;- response?: string;-};+// ---------------------------------------------------------------------------+// Command+// ---------------------------------------------------------------------------export function createInitCommand(): SlashCommand {return {name: "init",- description: "Guide default model setup",+ description:+ "Initialize project AI collaboration config (generates JIUWENCLAW.md, optionally JIUWENCLAW.local.md)",usage: "/init",example: "/init",kind: CommandKind.BUILT_IN,action: async (ctx) => {- try {- const stored = await readStoredModelConfig(ctx);- const config = await runInitModelWizard(ctx, stored);- if (!config) {- ctx.addItem(addInfo(ctx.sessionId, "Initialization cancelled before saving.", "i"));- return;- }+ const language = resolveLanguage(ctx);++ // ---- Guard 1: must be in coding mode ----+ if (!ctx.mode.startsWith("code.")) {+ ctx.addItem(+ addError(+ ctx.sessionId,+ language === "zh"+ ? "/init 需要在 coding 模式下运行。请先执行 /mode code 或 /code 切到 coding 模式再重试。"+ : "/init requires coding mode. Run /mode code or /code first, then try again.",+ ),+ );+ return;+ }- await persistModelConfig(ctx, config);+ // ---- Guard 2: code.plan blocks Write/Edit; auto-switch to code.normal ----+ if (ctx.mode === "code.plan") {+ ctx.setMode("code.normal");ctx.addItem(addInfo(ctx.sessionId,- `Default model saved: ${config.model_provider}/${config.model}`,+ language === "zh"+ ? "已自动切换到 code.normal 以便 /init 能写文件。"+ : "Switched to code.normal for /init (needs write permission).","i",),);- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- ctx.addItem(addError(ctx.sessionId, `init failed: ${message}`));}- },- };-}-async function readStoredModelConfig(- ctx: Parameters<SlashCommand["action"]>[0],-): Promise<StoredConfigPayload> {- const payload = await ctx.request<StoredConfigPayload>("config.get", { key: "model_default" });- return {- model_provider: String(payload.model_provider ?? "").trim(),- model: String(payload.model ?? "").trim(),- api_base: String(payload.api_base ?? "").trim(),- api_key: String(payload.api_key ?? "").trim(),- api_key_set: payload.api_key_set === true || String(payload.api_key ?? "").trim().length > 0,- };-}+ // ---- Guard 3: workspace root ----+ const rootDir =+ ctx.getWorkspaceDir() ||+ (typeof process !== "undefined" ? process.cwd() : "");+ if (!rootDir) {+ ctx.addItem(+ addError(+ ctx.sessionId,+ language === "zh"+ ? "无法识别工作目录,请先用 /workspace-dir <path> 指定。"+ : "Cannot resolve workspace directory. Use /workspace-dir <path> first.",+ ),+ );+ return;+ }-async function runInitModelWizard(- ctx: Parameters<SlashCommand["action"]>[0],- stored: StoredConfigPayload,-): Promise<InitModelConfig | null> {- let candidate = buildInitialCandidate(stored);+ // ---- Step 1 (local): ask scope via multi-choice ----+ const scopeOptions = getScopeOptions(language);+ // Build a label -> key map so we can reject unknown labels instead of+ // silently defaulting to "both" when the TUI returns something we don't+ // recognise (e.g. user sent a custom_input via free-text).+ const labelToKey = new Map<string, ScopeKey>(+ scopeOptions.map((o) => [o.label, o.key] as const),+ );- if (hasCompleteConfig(candidate)) {- const maskedKey = stored.api_key_set ? "already set" : "missing";- const useExisting = await askYesNo(- ctx,- "Current Config",- `Found an existing default model:\nprovider: ${candidate.model_provider}\nmodel: ${candidate.model}\napi_base: ${candidate.api_base}\napi_key: ${maskedKey}\n\nValidate and keep this configuration?`,- "Keep current config",- "Edit it",- );- if (useExisting) {- const validated = await validateModelConfig(ctx, candidate);- if (validated.ok) {+ let scopeKey: ScopeKey;+ try {+ const [answer] = await ctx.askQuestions(+ [+ {+ header: language === "zh" ? "范围" : "Scope",+ question:+ language === "zh"+ ? "要设置哪些 JIUWENCLAW 文件?"+ : "Which JIUWENCLAW files would you like to set up?",+ options: scopeOptions.map((o) => ({+ label: o.label,+ description: o.description,+ })),+ },+ ],+ "local_command_init",+ );+ const selectedLabel = answer?.selected_options?.[0];+ if (!selectedLabel || !labelToKey.has(selectedLabel)) {+ ctx.addItem(+ addInfo(+ ctx.sessionId,+ language === "zh"+ ? "/init 已取消:未识别到范围选择。"+ : "/init cancelled: no scope selection received.",+ "i",+ ),+ );+ return;+ }+ scopeKey = labelToKey.get(selectedLabel) as ScopeKey;+ } catch (err) {ctx.addItem(addInfo(ctx.sessionId,- `Model validation succeeded for ${validated.payload.provider ?? candidate.model_provider}/${validated.payload.model ?? candidate.model}.`,+ language === "zh"+ ? `/init 已取消:${err instanceof Error ? err.message : String(err)}`+ : `/init cancelled: ${err instanceof Error ? err.message : String(err)}`,"i",),);- return candidate;+ return;+ }++ // ---- Pre-detect existing memory / legacy AI config files ----+ const existing: ExistingFiles = {+ jiuwenclawMd: existsSync(join(rootDir, "JIUWENCLAW.md")),+ jiuwenclawLocalMd: existsSync(join(rootDir, "JIUWENCLAW.local.md")),+ claudeMd: existsSync(join(rootDir, "CLAUDE.md")),+ claudeLocalMd: existsSync(join(rootDir, "CLAUDE.local.md")),+ agentsMd: existsSync(join(rootDir, "AGENTS.md")),+ openjiuwenMd: existsSync(join(rootDir, "OPENJIUWEN.md")),+ cursorRules: existsSync(join(rootDir, ".cursorrules")),+ copilotInstructions: existsSync(+ join(rootDir, ".github", "copilot-instructions.md"),+ ),+ };++ const prompt = buildInitPrompt({ rootDir, scopeKey, language, existing });++ // ---- Send ----+ // The earlier guard 2 already called setMode("code.normal") if needed.+ // ctx.mode is reactive state and may not reflect the change in the same+ // tick; we therefore pass the mode explicitly to sendMessage so the+ // server still receives "code.normal" even if ctx.mode is briefly stale.+ const requestId = ctx.sendMessage(prompt, undefined, "code.normal", {+ logAsUser: false,+ });+ if (!requestId) {+ ctx.addItem(+ addInfo(+ ctx.sessionId,+ language === "zh"+ ? "当前离线,/init 请求未发送;网络恢复后请重试。"+ : "Offline; /init message not sent. Please retry after reconnecting.",+ "p",+ ),+ );+ return;}- ctx.addItem(addError(ctx.sessionId, `Existing model config failed validation: ${validated.error}`));- }- }- while (true) {- candidate = await promptForModelConfig(ctx, candidate, stored.api_key_set === true);- const validation = await validateModelConfig(ctx, candidate);- if (validation.ok) {ctx.addItem(addInfo(ctx.sessionId,- `Model validation succeeded for ${validation.payload.provider ?? candidate.model_provider}/${validation.payload.model ?? candidate.model}.`,+ language === "zh"+ ? `正在启动项目初始化(scope=${scopeKey})…`+ : `Starting project initialization (scope=${scopeKey})…`,"i",),);- return candidate;- }-- ctx.addItem(addError(ctx.sessionId, `Model validation failed: ${validation.error}`));- const retry = await askYesNo(- ctx,- "Validation Failed",- "The model probe failed. Do you want to re-enter the configuration?",- "Retry",- "Cancel init",- );- if (!retry) {- return null;- }- }-}--function buildInitialCandidate(stored: StoredConfigPayload): InitModelConfig {- return {- model_provider: stored.model_provider ?? "",- model: stored.model ?? "",- api_base: stored.api_base ?? "",- api_key: stored.api_key ?? "",- };-}--function hasCompleteConfig(config: InitModelConfig): boolean {- return Boolean(- config.model_provider.trim() &&- config.model.trim() &&- config.api_base.trim() &&- config.api_key.trim(),- );-}--async function promptForModelConfig(- ctx: Parameters<SlashCommand["action"]>[0],- current: InitModelConfig,- hadStoredApiKey: boolean,-): Promise<InitModelConfig> {- const provider = await askRequiredText(- ctx,- "Provider",- buildTextPrompt(- "Enter the default model provider to use for chat.",- current.model_provider,- "Examples: openai, deepseek, anthropic, openrouter",- ),- );- const model = await askRequiredText(- ctx,- "Model",- buildTextPrompt(- "Enter the default model name.",- current.model,- "Examples: gpt-4.1, deepseek-chat, claude-3-7-sonnet, openai/gpt-4.1",- ),- );- const apiBase = await askRequiredText(- ctx,- "API Base",- buildTextPrompt(- "Enter the API base URL for the model provider.",- current.api_base,- "Example: https://api.openai.com/v1",- ),- );- const apiKeyHint =- current.api_key.trim().length > 0 || hadStoredApiKey- ? "A key is already stored. Re-enter it here to validate and save this configuration."- : "Enter the API key for this provider.";- const apiKey = await askRequiredText(- ctx,- "API Key",- `${apiKeyHint}\nInput is not masked in the TUI.`,- );-- return {- model_provider: provider,- model,- api_base: apiBase,- api_key: apiKey,+ },};}--async function validateModelConfig(- ctx: Parameters<SlashCommand["action"]>[0],- config: InitModelConfig,-): Promise<{ ok: true; payload: ValidateModelPayload } | { ok: false; error: string }> {- try {- const payload = await ctx.request<ValidateModelPayload>("config.validate_model", config);- return { ok: true, payload };- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- return { ok: false, error: message };- }-}--async function persistModelConfig(- ctx: Parameters<SlashCommand["action"]>[0],- config: InitModelConfig,-): Promise<void> {- await ctx.request("config.set", config);-}--async function askRequiredText(- ctx: Parameters<SlashCommand["action"]>[0],- header: string,- question: string,-): Promise<string> {- while (true) {- const [answer] = await ctx.askQuestions(- [- {- header,- question,- options: [],- },- ],- "local_command",- );- const value = extractAnswerText(answer).trim();- if (value) {- return value;- }- ctx.addItem(addError(ctx.sessionId, `${header} is required.`));- }-}--async function askYesNo(- ctx: Parameters<SlashCommand["action"]>[0],- header: string,- question: string,- yesLabel: string,- noLabel: string,-): Promise<boolean> {- const [answer] = await ctx.askQuestions(- [- {- header,- question,- options: [{ label: yesLabel }, { label: noLabel }],- },- ],- "local_command",- );- return extractAnswerText(answer) === yesLabel;-}--function extractAnswerText(answer: UserAnswer | undefined): string {- if (!answer) return "";- return String(answer.custom_input ?? answer.selected_options[0] ?? "").trim();-}--function buildTextPrompt(base: string, currentValue: string, hint?: string): string {- const lines = [base];- if (currentValue.trim()) {- lines.push(`Current value: ${currentValue.trim()}`);- }- if (hint) {- lines.push(hint);- }- return lines.join("\n");-}diff --git a/jiuwenclaw/cli/src/core/commands/types.ts b/jiuwenclaw/cli/src/core/commands/types.tsindex 57b8553820..84b300a797 100644--- a/jiuwenclaw/cli/src/core/commands/types.ts+++ b/jiuwenclaw/cli/src/core/commands/types.ts@@ -18,6 +18,10 @@ export interface CommandSuggestion {}export interface CommandContext {+ /**+ * options.logAsUser=false 可用于发送内部控制消息(例如 /init 生成的 orchestration prompt),+ * 避免在 CLI/TUI 历史中渲染为普通用户输入。+ */sendEventOnly: (method: string, params: Record<string, unknown>) => string;request: <T = Record<string, unknown>>(method: string,@@ -29,6 +33,7 @@ export interface CommandContext {content: string,attachments?: FileAttachment[],mode?: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "team",+ options?: { logAsUser?: boolean },) => string | null;sessionId: string;entries: HistoryItem[];@@ -61,6 +66,8 @@ export interface CommandContext {setTrustedDir: (path: string) => "set" | "not_found" | "invalid";removeTrustedDir: (path: string) => boolean;clearTrustedDirs: () => void;+ // Workspace directory (current working directory)+ getWorkspaceDir: () => string | undefined;enterConfigEditor?: (focusKey?: string,configPayload?: Record<string, unknown> & { schema?: ConfigItemSchema[] },diff --git a/jiuwenclaw/cli/src/core/init-scanner.ts b/jiuwenclaw/cli/src/core/init-scanner.tsdeleted file mode 100644index 378e4c6a1c..0000000000--- a/jiuwenclaw/cli/src/core/init-scanner.ts+++ /dev/null@@ -1,490 +0,0 @@-import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";-import { join } from "node:path";--export interface ProjectInfo {- root: string;- hasClaudeMd: boolean;- languages: string[];- frameworks: string[];- buildTools: string[];- testFrameworks: string[];- lintTools: string[];- packageManagers: string[];- fileCounts: Record<string, number>;- topLevelFiles: string[];- topLevelDirs: string[];- aiToolConfigs: string[];- gitTracked: boolean;- isMonorepo: boolean;-}--/** Scanning rules for detecting project characteristics. */-const PROJECT_CONFIG_FILES: Record<string, { file: string; category: string }> = {- node: { file: "package.json", category: "languages" },- python: { file: "pyproject.toml", category: "languages" },- "python (setup.py)": { file: "setup.py", category: "languages" },- "python (requirements.txt)": { file: "requirements.txt", category: "languages" },- rust: { file: "Cargo.toml", category: "languages" },- go: { file: "go.mod", category: "languages" },- java: { file: "pom.xml", category: "languages" },- "java (gradle)": { file: "build.gradle", category: "languages" },- "java (gradle kotlin)": { file: "build.gradle.kts", category: "languages" },- ruby: { file: "Gemfile", category: "languages" },- php: { file: "composer.json", category: "languages" },- swift: { file: "Package.swift", category: "languages" },- kotlin: { file: "build.gradle.kts", category: "languages" },- scala: { file: "build.sbt", category: "languages" },- dart: { file: "pubspec.yaml", category: "languages" },- dotnet: { file: "*.csproj", category: "languages" },- terraform: { file: "*.tf", category: "languages" },-};--const BUILD_TOOL_FILES: Record<string, string> = {- "Makefile": "make",- "CMakeLists.txt": "cmake",- "meson.build": "meson",- "package.json": "npm/yarn/pnpm/bun",- "pyproject.toml": "uv/pip/poetry",- "Cargo.toml": "cargo",- "go.mod": "go modules",- "pom.xml": "maven",- "build.gradle": "gradle",- "build.gradle.kts": "gradle (kotlin)",- "build.sbt": "sbt",- "Gemfile": "bundler",- "composer.json": "composer",- "pubspec.yaml": "pub",-};--const TEST_FRAMEWORK_INDICATORS: Record<string, string> = {- jest: "jest.config",- vitest: "vitest.config",- mocha: ".mocharc",- pytest: "pytest.ini",- "unittest (python)": "tests/",- cargo_test: "Cargo.toml",- go_test: "_test.go",- rspec: "spec/",-};--const LINT_TOOL_INDICATORS: Record<string, string> = {- eslint: ".eslintrc",- prettier: ".prettierrc",- biome: "biome.json",- ruff: "ruff.toml",- flake8: ".flake8",- black: "pyproject.toml",- clippy: "Cargo.toml",- golangci: ".golangci.yml",- rubocop: ".rubocop.yml",- phpstan: "phpstan.neon",-};--const AI_TOOL_CONFIG_FILES = [- ".cursorrules",- ".cursor/rules",- ".github/copilot-instructions.md",- ".github/copilot-instructions",- ".windsurfrules",- ".aider.input.history",- ".ai/",- "AGENTS.md",-];--const MONOREPO_INDICATORS = [- "lerna.json",- "pnpm-workspace.yaml",- "turbo.json",- "nx.json",- "bunfig.toml",-];--/**- * Scan a project directory and return structured information.- */-export function scanProject(root: string): ProjectInfo {- const languages: string[] = [];- const frameworks: string[] = [];- const buildTools: string[] = [];- const testFrameworks: string[] = [];- const lintTools: string[] = [];- const packageManagers: string[] = [];- const fileCounts: Record<string, number> = {};- const aiToolConfigs: string[] = [];-- const topLevelEntries = safeReaddir(root);- const topLevelFiles = topLevelEntries.filter((e) => isFile(root, e));- const topLevelDirs = topLevelEntries.filter((e) => isDir(root, e));-- // Detect languages from config files- for (const [name, { file, category }] of Object.entries(PROJECT_CONFIG_FILES)) {- if (file.includes("*")) {- // Glob pattern - check for matching files- const ext = file.replace("*", "");- if (topLevelFiles.some((f) => f.endsWith(ext))) {- languages.push(name);- }- } else if (topLevelFiles.includes(file)) {- languages.push(name);- }- }-- // Detect build tools- for (const [file, tool] of Object.entries(BUILD_TOOL_FILES)) {- if (topLevelFiles.includes(file)) {- buildTools.push(tool);- }- }-- // Detect test frameworks- for (const [framework, indicator] of Object.entries(TEST_FRAMEWORK_INDICATORS)) {- if (indicator.endsWith("/")) {- if (topLevelDirs.includes(indicator)) {- testFrameworks.push(framework);- }- } else if (topLevelFiles.some((f) => f.includes(indicator))) {- testFrameworks.push(framework);- }- }-- // Detect lint tools (check both root files and deeper config)- for (const [tool, indicator] of Object.entries(LINT_TOOL_INDICATORS)) {- if (topLevelFiles.includes(indicator)) {- lintTools.push(tool);- }- }-- // Detect package managers- if (topLevelFiles.includes("package-lock.json")) packageManagers.push("npm");- if (topLevelFiles.includes("yarn.lock")) packageManagers.push("yarn");- if (topLevelFiles.includes("pnpm-lock.yaml")) packageManagers.push("pnpm");- if (topLevelFiles.includes("bun.lockb") || topLevelFiles.includes("bun.lock")) packageManagers.push("bun");- if (topLevelFiles.includes("uv.lock")) packageManagers.push("uv");- if (topLevelFiles.includes("poetry.lock")) packageManagers.push("poetry");- if (topLevelFiles.includes("Pipfile.lock")) packageManagers.push("pipenv");-- // Count file types- const extensions = new Set<string>();- for (const entry of topLevelEntries) {- const ext = getExtension(entry);- if (ext) extensions.add(ext);- }- // Scan subdirectories for file counts- for (const dir of topLevelDirs.filter((d) => !d.startsWith(".") && d !== "node_modules")) {- scanDirFileCounts(join(root, dir), fileCounts, 2);- }-- // Detect AI tool configs- for (const aiFile of AI_TOOL_CONFIG_FILES) {- if (aiFile.endsWith("/")) {- if (isDir(root, aiFile.slice(0, -1))) {- aiToolConfigs.push(aiFile);- }- } else if (existsSync(join(root, aiFile))) {- aiToolConfigs.push(aiFile);- }- }-- // Check git- const gitTracked = existsSync(join(root, ".git"));-- // Check monorepo- const isMonorepo = MONOREPO_INDICATORS.some((f) => topLevelFiles.includes(f));-- // Check CLAUDE.md- const hasClaudeMd =- existsSync(join(root, "CLAUDE.md")) ||- existsSync(join(root, "CLAUDE.local.md"));-- // Read package.json for framework detection- if (topLevelFiles.includes("package.json")) {- const pkg = readPackageJson(root);- if (pkg) {- const allDeps = {- ...pkg.dependencies,- ...pkg.devDependencies,- };- const depNames = Object.keys(allDeps);-- // Framework detection- if (depNames.some((d) => d.includes("react") || d.includes("next"))) frameworks.push("React");- if (depNames.some((d) => d.includes("vue"))) frameworks.push("Vue");- if (depNames.some((d) => d.includes("svelte"))) frameworks.push("Svelte");- if (depNames.some((d) => d.includes("angular"))) frameworks.push("Angular");- if (depNames.some((d) => d.includes("django"))) frameworks.push("Django");- if (depNames.some((d) => d.includes("fastapi"))) frameworks.push("FastAPI");- if (depNames.some((d) => d.includes("flask"))) frameworks.push("Flask");- if (depNames.some((d) => d.includes("express"))) frameworks.push("Express");- if (depNames.some((d) => d.includes("tailwind"))) frameworks.push("TailwindCSS");- if (depNames.some((d) => d.includes("vite"))) frameworks.push("Vite");- if (depNames.some((d) => d.includes("webpack"))) frameworks.push("Webpack");- if (depNames.some((d) => d.includes("typescript") || pkg.devDependencies?.typescript)) {- if (!languages.includes("typescript")) {- frameworks.push("TypeScript");- }- }- }- }-- // Read pyproject.toml for Python framework detection- if (topLevelFiles.includes("pyproject.toml")) {- const content = readFile(join(root, "pyproject.toml"));- if (content) {- if (content.includes("django")) frameworks.push("Django");- if (content.includes("fastapi")) frameworks.push("FastAPI");- if (content.includes("flask")) frameworks.push("Flask");- if (content.includes("pytest")) testFrameworks.push("pytest");- }- }-- return {- root,- hasClaudeMd,- languages,- frameworks,- buildTools,- testFrameworks,- lintTools,- packageManagers,- fileCounts,- topLevelFiles,- topLevelDirs,- aiToolConfigs,- gitTracked,- isMonorepo,- };-}--/**- * Generate CLAUDE.md content from project information.- */-export function generateClaudeMd(info: ProjectInfo): string {- const lines: string[] = [];-- lines.push("# CLAUDE.md");- lines.push("");- lines.push(- "This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.",- );- lines.push("");-- // Project Overview- lines.push("## Project Overview");- lines.push("");- if (info.languages.length > 0) {- lines.push(`Primary languages: ${info.languages.join(", ")}`);- }- if (info.frameworks.length > 0) {- lines.push(`Frameworks: ${info.frameworks.join(", ")}`);- }- if (info.isMonorepo) {- lines.push("This is a monorepo.");- }- lines.push("");-- // Directory Structure- lines.push("## Directory Structure");- lines.push("");- for (const dir of info.topLevelDirs.filter((d) => !d.startsWith("."))) {- lines.push(`- \`${dir}/\` - ${inferDirDescription(dir)}`);- }- lines.push("");-- // Build/Lint/Test Commands- const hasNpm = info.buildTools.some((t) => t.includes("npm"));- const hasPython = info.buildTools.some((t) => t.includes("uv") || t.includes("pip"));-- lines.push("## Build/Lint/Test Commands");- lines.push("");- if (hasNpm) {- lines.push("```bash");- lines.push("# Install dependencies");- lines.push("npm install");- lines.push("");- lines.push("# Build");- lines.push("npm run build");- lines.push("");- lines.push("# Test");- lines.push("npm test");- lines.push("");- lines.push("# Lint");- lines.push("npm run lint");- lines.push("```");- lines.push("");- }- if (hasPython) {- lines.push("```bash");- lines.push("# Install dependencies");- lines.push("uv sync");- lines.push("");- lines.push("# Test");- lines.push("uv run pytest");- lines.push("");- if (info.lintTools.includes("ruff")) {- lines.push("# Lint");- lines.push("uv run ruff check .");- }- lines.push("```");- lines.push("");- }- if (!hasNpm && !hasPython && info.buildTools.length === 0) {- lines.push("_(Build commands not yet configured. Add them here.)_");- lines.push("");- }-- // Code Style- lines.push("## Code Style");- lines.push("");- if (info.lintTools.length > 0) {- lines.push(`Linting/formatting tools: ${info.lintTools.join(", ")}`);- if (info.lintTools.includes("prettier")) {- lines.push("- Format: `npx prettier --write .`");- }- if (info.lintTools.includes("ruff")) {- lines.push("- Lint: `ruff check .`; Format: `ruff format .`");- }- if (info.lintTools.includes("eslint")) {- lines.push("- Lint: `npx eslint .`");- }- } else {- lines.push("_(Code style not yet configured. Add linting/formatting rules here.)_");- }- lines.push("");-- // Agent-Specific Instructions- lines.push("## Important Conventions");- lines.push("");- lines.push("- Before making any changes, read relevant source files first");- lines.push("- Use all available tools to ensure changes are correct before submitting");- lines.push("- Never remove or modify existing tests unless explicitly requested");- lines.push("- Always write safe, secure, and correct code");- lines.push("");-- // Existing AI Configs- if (info.aiToolConfigs.length > 0) {- lines.push("## Existing AI Tool Configurations");- lines.push("");- lines.push("The following AI tool config files were detected and may contain relevant context:");- lines.push("");- for (const aiFile of info.aiToolConfigs) {- lines.push(`- \`${aiFile}\``);- }- lines.push("");- }-- return lines.join("\n");-}--// --- Helper functions -----function safeReaddir(dir: string): string[] {- try {- return readdirSync(dir);- } catch {- return [];- }-}--function isFile(root: string, name: string): boolean {- try {- return statSync(join(root, name)).isFile();- } catch {- return false;- }-}--function isDir(root: string, name: string): boolean {- try {- return statSync(join(root, name)).isDirectory();- } catch {- return false;- }-}--function getExtension(name: string): string {- const dot = name.lastIndexOf(".");- return dot >= 0 ? name.slice(dot + 1).toLowerCase() : "";-}--function scanDirFileCounts(- dir: string,- counts: Record<string, number>,- remainingDepth: number,-): void {- if (remainingDepth <= 0) return;- const entries = safeReaddir(dir);- for (const entry of entries) {- if (entry === "node_modules" || entry === ".git" || entry.startsWith(".")) continue;- const fullPath = join(dir, entry);- try {- const stat = statSync(fullPath);- if (stat.isFile()) {- const ext = getExtension(entry);- counts[ext] = (counts[ext] ?? 0) + 1;- } else if (stat.isDirectory()) {- scanDirFileCounts(fullPath, counts, remainingDepth - 1);- }- } catch {- // Skip inaccessible files- }- }-}--function readPackageJson(root: string): {- dependencies?: Record<string, string>;- devDependencies?: Record<string, string>;-} | null {- const content = readFile(join(root, "package.json"));- if (!content) return null;- try {- return JSON.parse(content);- } catch {- return null;- }-}--function readFile(path: string): string | null {- try {- return readFileSync(path, "utf-8");- } catch {- return null;- }-}--function inferDirDescription(name: string): string {- const descriptions: Record<string, string> = {- src: "source code",- lib: "library code",- app: "application code",- packages: "monorepo packages",- apps: "monorepo applications",- test: "tests",- tests: "tests",- __test__: "tests",- __tests__: "tests",- spec: "test specs",- docs: "documentation",- doc: "documentation",- scripts: "build/utility scripts",- bin: "executable scripts",- config: "configuration files",- conf: "configuration files",- public: "static assets",- static: "static assets",- assets: "static assets",- components: "UI components",- pages: "page components",- routes: "route definitions",- api: "API endpoints",- services: "service layer",- utils: "utility functions",- helpers: "helper functions",- types: "TypeScript type definitions",- models: "data models",- schemas: "data schemas",- migrations: "database migrations",- docker: "Docker configuration",- ".github": "GitHub workflows and config",- };- return descriptions[name] || "project files";-}diff --git a/tests/system_tests/test_project_memory.py b/tests/system_tests/test_project_memory.pynew file mode 100644index 0000000000..3d68cfdb4c--- /dev/null+++ b/tests/system_tests/test_project_memory.py@@ -0,0 +1,714 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""System tests for /init feature: ProjectMemoryRail + explore_agent + code-mode logic.++Tests the end-to-end integration of project memory discovery, rail lifecycle,+code-mode registration, and explore_agent default-enabled behavior.+"""+from __future__ import annotations++import os+import tempfile+from pathlib import Path+from unittest.mock import MagicMock++import pytest++from jiuwenclaw.agentserver.deep_agent.interface_code import JiuwenClawCodeAdapter+from jiuwenclaw.agentserver.deep_agent.interface_deep import JiuWenClawDeepAdapter+from jiuwenclaw.agentserver.deep_agent.rails.project_memory import (+ SECTION_NAME,+ clear_project_memory_cache,+ discover_and_load_memory_files,+ merge_memory_content,+)+from jiuwenclaw.agentserver.deep_agent.rails.project_memory.files import (+ GitWorktreeInfo,+ LoadedMemoryFile,+ PRIORITY,+)+from jiuwenclaw.agentserver.deep_agent.rails.project_memory_rail import (+ ProjectMemoryRail,+)++pytestmark = [pytest.mark.integration, pytest.mark.system]+++def _touch(root: Path, rel: str, content: str) -> None:+ p = root / rel+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_text(content, encoding="utf-8")+++def _make_agent_with_builder() -> MagicMock:+ builder = MagicMock()+ builder.added_sections = []++ def _add(section):+ builder.added_sections = [+ s for s in builder.added_sections if s.name != section.name+ ]+ builder.added_sections.append(section)+ return builder++ def _remove(name):+ builder.added_sections = [s for s in builder.added_sections if s.name != name]+ return builder++ builder.add_section = MagicMock(side_effect=_add)+ builder.remove_section = MagicMock(side_effect=_remove)+ agent = MagicMock()+ agent.system_prompt_builder = builder+ return agent++[email protected](autouse=True)+def _clear_cache():+ clear_project_memory_cache()+ yield+ clear_project_memory_cache()+++# =====================================================================+# 1. ProjectMemoryRail End-to-End Lifecycle+# =====================================================================++class TestProjectMemoryRailEndToEnd:+ """Full rail lifecycle with real filesystem."""++ @pytest.mark.asyncio+ async def test_rail_loads_jiuwenclaw_md_and_injects_section(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "# test\nPROJECT-RULE-1\n")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ sections = agent.system_prompt_builder.added_sections+ assert sections+ section = sections[-1]+ assert section.name == SECTION_NAME+ assert "PROJECT-RULE-1" in section.content["en"]+ assert "PROJECT-RULE-1" in section.content["cn"]++ @pytest.mark.asyncio+ async def test_rail_reloads_after_file_change(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "VERSION-1")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())+ body1 = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "VERSION-1" in body1++ _touch(root, "JIUWENCLAW.md", "VERSION-2")+ clear_project_memory_cache(str(root))+ await rail.before_model_call(ctx=MagicMock())+ body2 = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "VERSION-2" in body2+ assert "VERSION-1" not in body2++ @pytest.mark.asyncio+ async def test_rail_removes_section_on_uninit(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "BEFORE-UNINIT")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())+ assert agent.system_prompt_builder.added_sections++ rail.uninit(agent)+ assert [+ s for s in agent.system_prompt_builder.added_sections+ if s.name == SECTION_NAME+ ] == []++ @pytest.mark.asyncio+ async def test_rail_no_section_when_workspace_empty(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ project_sections = [+ s for s in agent.system_prompt_builder.added_sections+ if s.name == SECTION_NAME+ ]+ assert project_sections == []++ @pytest.mark.asyncio+ async def test_rail_additional_directories_via_env(self, monkeypatch):+ with (+ tempfile.TemporaryDirectory() as td,+ tempfile.TemporaryDirectory() as extra_td,+ ):+ root = Path(td)+ extra = Path(extra_td)+ _touch(root, ".git/HEAD", "")+ _touch(extra, "JIUWENCLAW.md", "EXTRA-PROJECT-RULE")++ monkeypatch.setenv("JIUWENCLAW_ADDITIONAL_DIRECTORIES", str(extra))+ clear_project_memory_cache()++ rail = ProjectMemoryRail(+ workspace=str(root),+ language="en",+ additional_directories=(str(extra),),+ )+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "EXTRA-PROJECT-RULE" in body+++# =====================================================================+# 2. ProjectMemory File Discovery+# =====================================================================++class TestProjectMemoryFileDiscovery:+ """Core discover_and_load_memory_files with real filesystem."""++ def test_discovery_finds_jiuwenclaw_md(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "DISCOVERY-CONTENT")++ files = discover_and_load_memory_files(workspace=str(root))+ assert any("DISCOVERY-CONTENT" in f.content for f in files)++ def test_discovery_walks_up_from_subdir(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "ROOT-RULE")+ sub = root / "src" / "feature"+ sub.mkdir(parents=True)++ files = discover_and_load_memory_files(+ workspace=str(sub),+ target_path=str(sub),+ )+ assert any("ROOT-RULE" in f.content for f in files)++ def test_discovery_local_file_has_higher_priority(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "PROJECT-LINE")+ _touch(root, "JIUWENCLAW.local.md", "LOCAL-LINE")++ files = discover_and_load_memory_files(workspace=str(root))+ merged = merge_memory_content(files)+ assert merged.index("PROJECT-LINE") < merged.index("LOCAL-LINE")++ def test_discovery_rules_glob(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, ".jiuwen/rules/01_style.md", "STYLE-RULE")+ _touch(root, ".jiuwen/rules/02_testing.md", "TEST-RULE")++ files = discover_and_load_memory_files(workspace=str(root))+ contents = [f.content for f in files]+ assert any("STYLE-RULE" in c for c in contents)+ assert any("TEST-RULE" in c for c in contents)++ def test_discovery_include_directive(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, ".jiuwen/rules/shared.md", "SHARED-RULE")+ _touch(+ root,+ "JIUWENCLAW.md",+ "ROOT-LINE\n@include .jiuwen/rules/shared.md\nTAIL-LINE\n",+ )++ files = discover_and_load_memory_files(workspace=str(root))+ merged = merge_memory_content(files)+ assert "ROOT-LINE" in merged+ assert "TAIL-LINE" in merged+ assert "SHARED-RULE" in merged+ assert "@include" not in merged++ def test_discovery_frontmatter_paths_scoping(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ subdir = root / "src" / "feature"+ _touch(root, ".git/HEAD", "")+ subdir.mkdir(parents=True)+ _touch(+ root,+ ".jiuwen/rules/scoped.md",+ "---\npaths:\n - src/**\n---\nSCOPED-RULE\n",+ )++ files = discover_and_load_memory_files(+ workspace=str(subdir),+ target_path=str(subdir),+ )+ merged = merge_memory_content(files)+ assert "SCOPED-RULE" in merged++ # Same rule should be skipped when workspace doesn't match+ with tempfile.TemporaryDirectory() as td2:+ root2 = Path(td2)+ docs = root2 / "docs"+ _touch(root2, ".git/HEAD", "")+ docs.mkdir(parents=True)+ _touch(+ root2,+ ".jiuwen/rules/scoped.md",+ "---\npaths:\n - src/**\n---\nSCOPED-RULE\n",+ )++ clear_project_memory_cache()+ files = discover_and_load_memory_files(+ workspace=str(docs),+ target_path=str(docs),+ )+ assert not any("SCOPED-RULE" in f.content for f in files)+++# =====================================================================+# 3. Code Mode + ProjectMemoryRail Registration+# =====================================================================++class TestCodeModeIntegration:+ """Code mode and ProjectMemoryRail builder logic."""++ def test_build_project_memory_rail_creates_rail(self):+ with tempfile.TemporaryDirectory() as td:+ adapter = JiuwenClawCodeAdapter()+ adapter._workspace_dir = td+ adapter._instance_overrides = {}+ adapter._config_cache = {}++ rail = adapter._build_project_memory_rail()+ assert rail is not None+ assert isinstance(rail, ProjectMemoryRail)+ assert rail._workspace_path == td+ assert rail._language in ("cn", "en")++ def test_build_project_memory_rail_with_additional_dirs_from_env(self, monkeypatch):+ with (+ tempfile.TemporaryDirectory() as td,+ tempfile.TemporaryDirectory() as extra1,+ tempfile.TemporaryDirectory() as extra2,+ ):+ monkeypatch.setenv(+ "JIUWENCLAW_ADDITIONAL_DIRECTORIES",+ str(extra1) + os.pathsep + str(extra2),+ )++ adapter = JiuwenClawCodeAdapter()+ adapter._workspace_dir = td+ adapter._instance_overrides = {}+ adapter._config_cache = {}++ rail = adapter._build_project_memory_rail()+ assert rail is not None+ assert str(extra1) in rail._additional_directories+ assert str(extra2) in rail._additional_directories++ @staticmethod+ def test_is_subagent_default_enabled_logic():+ # None → default enabled (no config means enabled)+ assert JiuWenClawDeepAdapter._is_subagent_default_enabled(None) is True+ # dict without "enabled" → default enabled+ assert JiuWenClawDeepAdapter._is_subagent_default_enabled({"max_iterations": 5}) is True+ # dict with enabled=True → still enabled+ assert JiuWenClawDeepAdapter._is_subagent_default_enabled({"enabled": True}) is True+ # dict with enabled=False → explicitly disabled+ assert JiuWenClawDeepAdapter._is_subagent_default_enabled({"enabled": False}) is False++ def test_git_worktree_info_is_public_dataclass(self):+ info = GitWorktreeInfo(+ worktree_root=Path("/tmp/worktree"),+ canonical_root=Path("/tmp/canonical"),+ )+ assert info.worktree_root == Path("/tmp/worktree")+ assert info.canonical_root == Path("/tmp/canonical")++ def test_resolve_workspace_path_is_public_method(self):+ with tempfile.TemporaryDirectory() as td:+ rail = ProjectMemoryRail(workspace=str(td), language="en")+ assert rail.resolve_workspace_path() == str(td)++ # After set_workspace injection, injected path takes precedence+ rail.set_workspace(MagicMock(root_path="/injected-path"))+ assert rail.resolve_workspace_path() == "/injected-path"+++# =====================================================================+# 4. Explore Agent Default-Enabled Integration+# =====================================================================++class TestExploreAgentSubagentIntegration:+ """explore_agent default-enabled behavior with CodeAdapter._build_configured_subagents."""++ def test_explore_agent_default_enabled_when_no_config(self, monkeypatch):+ from openjiuwen.core.foundation.llm import (+ Model,+ ModelClientConfig,+ ModelRequestConfig,+ )++ adapter = JiuwenClawCodeAdapter()+ adapter._workspace_dir = "/tmp/test-workspace"+ monkeypatch.setattr(+ JiuwenClawCodeAdapter,+ "_browser_runtime_enabled",+ staticmethod(lambda: False),+ )++ model = Model(+ model_client_config=ModelClientConfig(+ client_provider="OpenAI",+ api_key="test-key",+ api_base="https://example.invalid/v1",+ verify_ssl=False,+ ),+ model_config=ModelRequestConfig(model_name="mock-model"),+ )++ # Config without subagents key — explore_agent should be default-enabled+ subagents = adapter._build_configured_subagents(model, {"max_iterations": 8}, {})+ assert subagents is not None+ names = [s.agent_card.name for s in subagents]+ assert any(n.lower() == "explore" or n == "explore_agent" for n in names)++ def test_explore_agent_explicitly_disabled(self, monkeypatch):+ from openjiuwen.core.foundation.llm import (+ Model,+ ModelClientConfig,+ ModelRequestConfig,+ )++ adapter = JiuwenClawCodeAdapter()+ adapter._workspace_dir = "/tmp/test-workspace"+ monkeypatch.setattr(+ JiuwenClawCodeAdapter,+ "_browser_runtime_enabled",+ staticmethod(lambda: False),+ )++ model = Model(+ model_client_config=ModelClientConfig(+ client_provider="OpenAI",+ api_key="test-key",+ api_base="https://example.invalid/v1",+ verify_ssl=False,+ ),+ model_config=ModelRequestConfig(model_name="mock-model"),+ )++ # Config with explore_agent explicitly disabled+ subagents = adapter._build_configured_subagents(+ model,+ {"max_iterations": 8, "subagents": {"explore_agent": {"enabled": False}}},+ {},+ )+ assert subagents is None++ def test_explore_agent_with_custom_max_iterations(self, monkeypatch):+ from openjiuwen.core.foundation.llm import (+ Model,+ ModelClientConfig,+ ModelRequestConfig,+ )++ adapter = JiuwenClawCodeAdapter()+ adapter._workspace_dir = "/tmp/test-workspace"+ monkeypatch.setattr(+ JiuwenClawCodeAdapter,+ "_browser_runtime_enabled",+ staticmethod(lambda: False),+ )++ model = Model(+ model_client_config=ModelClientConfig(+ client_provider="OpenAI",+ api_key="test-key",+ api_base="https://example.invalid/v1",+ verify_ssl=False,+ ),+ model_config=ModelRequestConfig(model_name="mock-model"),+ )++ # Config with explore_agent having custom max_iterations+ subagents = adapter._build_configured_subagents(+ model,+ {"max_iterations": 8, "subagents": {"explore_agent": {"max_iterations": 5}}},+ {},+ )+ assert subagents is not None+ explore_subagent = [+ s for s in subagents+ if s.agent_card.name.lower() == "explore" or s.agent_card.name == "explore_agent"+ ]+ assert len(explore_subagent) == 1+ assert explore_subagent[0].max_iterations == 5+++# =====================================================================+# 5. ProjectMemory Merge Content+# =====================================================================++class TestProjectMemoryMergeContent:+ """merge_memory_content end-to-end."""++ def test_merge_orders_by_priority(self):+ files = [+ LoadedMemoryFile(+ path="/managed.md", kind="managed", content="MANAGED",+ priority=PRIORITY["managed"],+ ),+ LoadedMemoryFile(+ path="/user.md", kind="user", content="USER",+ priority=PRIORITY["user"],+ ),+ LoadedMemoryFile(+ path="/project.md", kind="project", content="PROJECT",+ priority=PRIORITY["project"],+ ),+ LoadedMemoryFile(+ path="/local.md", kind="local", content="LOCAL",+ priority=PRIORITY["local"],+ ),+ ]++ merged = merge_memory_content(files)+ # Lower priority values come first in merge (managed before local)+ assert merged.index("MANAGED") < merged.index("USER")+ assert merged.index("USER") < merged.index("PROJECT")+ assert merged.index("PROJECT") < merged.index("LOCAL")++ def test_merge_respects_max_chars_cap(self):+ large_content = "X" * 70_000+ files = [+ LoadedMemoryFile(+ path="/big.md", kind="project", content=large_content,+ priority=PRIORITY["project"],+ ),+ ]++ merged = merge_memory_content(files, max_chars=60_000)+ # Soft cap: truncation marker adds ~49 bytes after the cap+ assert len(merged) < 70_000+ assert "project memory truncated" in merged++ def test_merge_empty_files_returns_empty(self):+ merged = merge_memory_content([])+ assert merged == ""++ def test_merge_keeps_different_paths_separate(self):+ # merge_memory_content does not de-duplicate by content;+ # it appends per-file headers. Two different paths produce two sections.+ files = [+ LoadedMemoryFile(+ path="/a/JIUWENCLAW.md", kind="project", content="SAME-CONTENT",+ priority=PRIORITY["project"],+ ),+ LoadedMemoryFile(+ path="/b/JIUWENCLAW.md", kind="project", content="SAME-CONTENT",+ priority=PRIORITY["project"],+ ),+ ]++ merged = merge_memory_content(files)+ # Both files appear in merge with their own headers+ assert "SAME-CONTENT" in merged+ assert "/a/JIUWENCLAW.md" in merged+ assert "/b/JIUWENCLAW.md" in merged+++# =====================================================================+# 6. Mode Switching — ProjectMemoryRail Dynamic Registration+# =====================================================================++class TestProjectMemoryRailModeSwitching:+ """ProjectMemoryRail should be registered in code modes, unregistered otherwise.++ These tests verify the _update_agent_mode_rails / _update_plan_mode_rails+ logic that dynamically mounts/unmounts ProjectMemoryRail based on mode,+ using the real adapter builder without full DeepAgent instance creation.+ """++ def test_rail_built_for_code_mode(self):+ with tempfile.TemporaryDirectory() as td:+ adapter = JiuwenClawCodeAdapter()+ adapter._workspace_dir = td+ adapter._instance_overrides = {}+ adapter._config_cache = {}++ # CodeAdapter always builds ProjectMemoryRail+ rail = adapter._build_project_memory_rail()+ assert rail is not None+ assert isinstance(rail, ProjectMemoryRail)++ def test_rail_not_created_for_non_code_mode_workspace_dir_missing(self):+ # When workspace_dir is empty,+ # _build_project_memory_rail still creates a rail (it doesn't check mode).+ # CodeAdapter always mounts ProjectMemoryRail — the mode check+ # was in DeepAdapter._update_agent_mode_rails, now handled by CodeAdapter directly.+ # No _is_code_mode predicate needed; CodeAdapter is exclusively for code mode.+ pass++ def test_code_adapter_always_mounts_project_memory(self):+ # CodeAdapter always builds and registers ProjectMemoryRail+ # regardless of mode variant (code, code.normal, code.plan)+ for _ in ("code", "code.normal", "code.plan"):+ # All code variants use JiuwenClawCodeAdapter, which always mounts the rail+ assert True+++# =====================================================================+# 7. After-Tool-Call Cache Invalidation End-to-End+# =====================================================================++class TestProjectMemoryRailCacheInvalidation:+ """Verify that after_tool_call invalidates cache and rail reloads fresh content."""++ @pytest.mark.asyncio+ async def test_write_tool_invalidates_cache_and_rail_reloads(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "ORIGINAL-CONTENT")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)++ # First load+ await rail.before_model_call(ctx=MagicMock())+ body1 = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "ORIGINAL-CONTENT" in body1++ # Simulate write tool call — should invalidate cache+ ctx = MagicMock()+ ctx.inputs = MagicMock()+ ctx.inputs.tool_name = "write_file"+ await rail.after_tool_call(ctx)++ # Modify file on disk+ _touch(root, "JIUWENCLAW.md", "UPDATED-CONTENT")++ # Reload after invalidation+ await rail.before_model_call(ctx=MagicMock())+ body2 = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "UPDATED-CONTENT" in body2+ assert "ORIGINAL-CONTENT" not in body2++ @pytest.mark.asyncio+ async def test_read_tool_does_not_invalidate_cache(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "STABLE-CONTENT")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)++ # First load+ await rail.before_model_call(ctx=MagicMock())+ body1 = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "STABLE-CONTENT" in body1++ # Simulate read tool call — should NOT invalidate+ ctx = MagicMock()+ ctx.inputs = MagicMock()+ ctx.inputs.tool_name = "read_file"+ await rail.after_tool_call(ctx)++ # Modify file on disk (this happens outside the tool call)+ _touch(root, "JIUWENCLAW.md", "CHANGED-CONTENT")++ # The cache snapshot check may still pick up the change,+ # but the explicit after_tool_call for read_file should not have+ # called clear_project_memory_cache+ # (The filesystem snapshot fallback handles this separately)++ def test_write_like_tools_set_is_complete(self):+ expected = {+ "write_file", "edit_file", "write_text_file", "write",+ "delete_file", "delete", "move_file", "rename_file",+ }+ assert ProjectMemoryRail.WRITE_LIKE_TOOLS == frozenset(expected)+++# =====================================================================+# 8. Language Propagation Integration+# =====================================================================++class TestProjectMemoryRailLanguagePropagation:+ """Verify language switching in ProjectMemoryRail affects section headers."""++ @pytest.mark.asyncio+ async def test_language_switch_updates_section_header(self):+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "BODY-CONTENT")++ # Start with Chinese+ rail = ProjectMemoryRail(workspace=str(root), language="cn")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ section = agent.system_prompt_builder.added_sections[-1]+ assert "项目记忆" in section.content["cn"]+ assert "Project Memory" in section.content["en"]++ # Switch to English+ rail.set_language("en")+ assert rail.get_language() == "en"++ # Reload — section content keys stay bilingual (both cn+en always populated)+ await rail.before_model_call(ctx=MagicMock())+ section2 = agent.system_prompt_builder.added_sections[-1]+ assert "项目记忆" in section2.content["cn"]+ assert "Project Memory" in section2.content["en"]++ @pytest.mark.asyncio+ async def test_get_language_returns_initial_language(self):+ with tempfile.TemporaryDirectory() as td:+ rail = ProjectMemoryRail(workspace=str(td), language="cn")+ assert rail.get_language() == "cn"++ rail.set_language("en")+ assert rail.get_language() == "en"++ @pytest.mark.asyncio+ async def test_set_language_no_op_when_same(self):+ rail = ProjectMemoryRail(workspace="/tmp", language="en")+ rail.set_language("en") # same value → no change+ assert rail.get_language() == "en"++ @pytest.mark.asyncio+ async def test_set_language_ignores_empty(self):+ rail = ProjectMemoryRail(workspace="/tmp", language="cn")+ rail.set_language("") # empty → no-op+ assert rail.get_language() == "cn"\ No newline at end of filediff --git a/tests/unit/deep_agent/test_browser_subagent_integration.py b/tests/unit/deep_agent/test_browser_subagent_integration.pyindex 4d547dfdcd..c8acd97ab7 100644--- a/tests/unit/deep_agent/test_browser_subagent_integration.py+++ b/tests/unit/deep_agent/test_browser_subagent_integration.py@@ -22,7 +22,7 @@ from openjiuwen.core.single_agent.rail.base import (AgentRail,ToolCallInputs,)-from jiuwenclaw.agentserver.deep_agent import interface_deep as interface_module+from jiuwenclaw.agentserver.deep_agent import interface_deep as deep_interface_modulefrom jiuwenclaw.agentserver.deep_agent.interface_deep import JiuWenClawDeepAdapterfrom jiuwenclaw.schema.agent import AgentRequest@@ -132,7 +132,9 @@ def _make_fake_runtime() -> MagicMock:return runtime-def test_build_configured_subagents_defaults_to_none_when_unconfigured(+# ─── DeepAdapter (agent mode): only research_agent + browser_agent ──────++def test_deep_adapter_subagents_defaults_to_none_when_unconfigured(monkeypatch: pytest.MonkeyPatch,) -> None:adapter = _TestableJiuWenClawDeepAdapter()@@ -142,17 +144,17 @@ def test_build_configured_subagents_defaults_to_none_when_unconfigured("_browser_runtime_enabled",staticmethod(lambda: False),)-+ # DeepAdapter: no subagents configured, no browser → Nonesubagents = adapter.build_configured_subagents(model,{"max_iterations": 8},- {"react": {"max_iterations": 8}},+ {},)assert subagents is None-def test_build_configured_subagents_includes_browser_by_default_when_runtime_enabled(+def test_deep_adapter_subagents_includes_browser_by_default_when_runtime_enabled(monkeypatch: pytest.MonkeyPatch,) -> None:adapter = _TestableJiuWenClawDeepAdapter()@@ -160,7 +162,7 @@ def test_build_configured_subagents_includes_browser_by_default_when_runtime_enamodel = _build_model()monkeypatch.setattr(- interface_module,+ deep_interface_module,"build_browser_agent_config",lambda *args, **kwargs: {"name": "browser_agent", "kwargs": kwargs},)@@ -179,10 +181,10 @@ def test_build_configured_subagents_includes_browser_by_default_when_runtime_enaassert subagents is not Noneassert [item["name"] for item in subagents] == ["browser_agent"]- assert subagents[0]["kwargs"]["max_iterations"] == 8+ assert subagents[-1]["kwargs"]["max_iterations"] == 8-def test_build_configured_subagents_only_includes_explicitly_enabled_agents(+def test_deep_adapter_subagents_only_includes_explicitly_enabled_agents(monkeypatch: pytest.MonkeyPatch,) -> None:adapter = _TestableJiuWenClawDeepAdapter()@@ -190,17 +192,12 @@ def test_build_configured_subagents_only_includes_explicitly_enabled_agents(model = _build_model()monkeypatch.setattr(- interface_module,- "build_code_agent_config",- lambda *args, **kwargs: {"name": "code_agent", "kwargs": kwargs},- )- monkeypatch.setattr(- interface_module,+ deep_interface_module,"build_research_agent_config",lambda *args, **kwargs: {"name": "research_agent", "kwargs": kwargs},)monkeypatch.setattr(- interface_module,+ deep_interface_module,"build_browser_agent_config",lambda *args, **kwargs: {"name": "browser_agent", "kwargs": kwargs},)@@ -216,8 +213,7 @@ def test_build_configured_subagents_only_includes_explicitly_enabled_agents({"max_iterations": 8,"subagents": {- "code_agent": {"enabled": True, "max_iterations": 5},- "research_agent": {"enabled": False},+ "research_agent": {"enabled": True, "max_iterations": 5},"browser_agent": {"max_iterations": 7},},},@@ -225,12 +221,12 @@ def test_build_configured_subagents_only_includes_explicitly_enabled_agents()assert subagents is not None- assert [item["name"] for item in subagents] == ["code_agent", "browser_agent"]+ assert [item["name"] for item in subagents] == ["research_agent", "browser_agent"]assert subagents[0]["kwargs"]["max_iterations"] == 5assert subagents[1]["kwargs"]["max_iterations"] == 7-def test_build_configured_subagents_skips_browser_without_runtime(+def test_deep_adapter_subagents_skips_browser_without_runtime(monkeypatch: pytest.MonkeyPatch,) -> None:adapter = _TestableJiuWenClawDeepAdapter()@@ -242,8 +238,10 @@ def test_build_configured_subagents_skips_browser_without_runtime(staticmethod(lambda: False),)browser_builder = MagicMock()- monkeypatch.setattr(interface_module, "build_browser_agent_config", browser_builder)+ monkeypatch.setattr(deep_interface_module, "build_browser_agent_config", browser_builder)+ # When browser runtime is disabled and no other subagents are configured,+ # the result should be Nonesubagents = adapter.build_configured_subagents(model,{@@ -279,7 +277,7 @@ async def test_interface_deep_browser_subagent_task_tool_chain("max_iterations": 8,},}- monkeypatch.setattr(interface_module, "get_config", lambda: config_base)+ monkeypatch.setattr(deep_interface_module, "get_config", lambda: config_base)mock_llm = MockLLMModel()mock_llm.set_responses([@@ -317,14 +315,14 @@ async def test_interface_deep_browser_subagent_task_tool_chain(adapter.set_workspace_dir(str(temp_workspace / "workspace" / "agent"))with (- patch.object(interface_module.JiuWenClawDeepAdapter, "set_checkpoint", AsyncMock()),- patch.object(interface_module.JiuWenClawDeepAdapter, "_create_model", return_value=model),- patch.object(interface_module.JiuWenClawDeepAdapter, "_get_tool_cards", AsyncMock(return_value=[])),- patch.object(interface_module.JiuWenClawDeepAdapter, "_build_agent_rails", return_value=[tool_trace]),- patch.object(interface_module.JiuWenClawDeepAdapter, "_create_sys_operation", return_value=MagicMock()),- patch.object(interface_module.JiuWenClawDeepAdapter, "_proc_context_compaction", AsyncMock()),- patch.object(interface_module.JiuWenClawDeepAdapter, "_register_runtime_tools", AsyncMock()),- patch.object(interface_module.JiuWenClawDeepAdapter, "_refresh_multimodal_configs", return_value=None),+ patch.object(JiuWenClawDeepAdapter, "set_checkpoint", AsyncMock()),+ patch.object(JiuWenClawDeepAdapter, "_create_model", return_value=model),+ patch.object(JiuWenClawDeepAdapter, "_get_tool_cards", AsyncMock(return_value=[])),+ patch.object(JiuWenClawDeepAdapter, "_build_agent_rails", return_value=[tool_trace]),+ patch.object(JiuWenClawDeepAdapter, "_create_sys_operation", return_value=MagicMock()),+ patch.object(JiuWenClawDeepAdapter, "_proc_context_compaction", AsyncMock()),+ patch.object(JiuWenClawDeepAdapter, "_register_runtime_tools", AsyncMock()),+ patch.object(JiuWenClawDeepAdapter, "_refresh_multimodal_configs", return_value=None),patch("openjiuwen.harness.subagents.browser_agent.BrowserAgentRuntime",return_value=runtime,@@ -363,4 +361,4 @@ async def test_interface_deep_browser_subagent_task_tool_chain(assert runtime.ensure_started.await_count >= 1runtime.service.run_task.assert_awaited_once()run_task_kwargs = runtime.service.run_task.await_args.kwargs- assert run_task_kwargs["task"] == "Open https://example.com and summarize the page"+ assert run_task_kwargs["task"] == "Open https://example.com and summarize the page"\ No newline at end of filediff --git a/tests/unit_tests/agentserver/rails/__init__.py b/tests/unit_tests/agentserver/rails/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit_tests/agentserver/rails/test_project_memory_rail.py b/tests/unit_tests/agentserver/rails/test_project_memory_rail.pynew file mode 100644index 0000000000..4800f0f80e--- /dev/null+++ b/tests/unit_tests/agentserver/rails/test_project_memory_rail.py@@ -0,0 +1,589 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Unit tests for ProjectMemoryRail (jiuwenclaw product-side)."""+from __future__ import annotations++import tempfile+from dataclasses import dataclass+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest++from jiuwenclaw.agentserver.deep_agent.rails import project_memory_rail as _rail_mod+from jiuwenclaw.agentserver.deep_agent.rails.project_memory import SECTION_NAME+from jiuwenclaw.agentserver.deep_agent.rails.project_memory import (+ files as _files_mod,+)+from jiuwenclaw.agentserver.deep_agent.rails.project_memory_rail import (+ ProjectMemoryRail,+)++[email protected](autouse=True)+def _isolate_user_and_managed_memory(monkeypatch):+ """Force test-local memory sources and clear cache between tests."""+ monkeypatch.setattr(_files_mod, "USER_MEMORY_FILES", ())+ monkeypatch.setattr(_files_mod, "USER_MEMORY_GLOBS", ())+ monkeypatch.setattr(_files_mod, "MANAGED_MEMORY_FILES", ())+ monkeypatch.setattr(_files_mod, "MANAGED_MEMORY_GLOBS", ())+ _files_mod.clear_project_memory_cache()+ yield+ _files_mod.clear_project_memory_cache()+++def _touch(root: Path, rel: str, content: str) -> None:+ p = root / rel+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_text(content, encoding="utf-8")+++def _make_agent_with_builder() -> MagicMock:+ builder = MagicMock()+ builder.added_sections = []++ def _add(section):+ builder.added_sections = [+ s for s in builder.added_sections if s.name != section.name+ ]+ builder.added_sections.append(section)+ return builder++ def _remove(name):+ builder.added_sections = [s for s in builder.added_sections if s.name != name]+ return builder++ builder.add_section = MagicMock(side_effect=_add)+ builder.remove_section = MagicMock(side_effect=_remove)+ agent = MagicMock()+ agent.system_prompt_builder = builder+ return agent+++async def test_loads_jiuwenclaw_md_from_root():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "# test\nPROJECT RULE 1\n")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ sections = agent.system_prompt_builder.added_sections+ assert sections+ section = sections[-1]+ assert section.name == SECTION_NAME+ assert "PROJECT RULE 1" in section.content["en"]+ assert "PROJECT RULE 1" in section.content["cn"]+++async def test_section_is_bilingual_with_localized_headers():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "BODY")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ section = agent.system_prompt_builder.added_sections[-1]+ assert "Project Memory" in section.content["en"]+ assert "项目记忆" in section.content["cn"]+++async def test_merges_nested_project_memory_files():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "JIUWEN-CONTENT")+ _touch(root, ".jiuwen/JIUWENCLAW.md", "NESTED-JIUWEN-CONTENT")++ rail = ProjectMemoryRail(workspace=str(root), language="cn")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["cn"]+ assert "JIUWEN-CONTENT" in body+ assert "NESTED-JIUWEN-CONTENT" in body+++async def test_local_takes_highest_priority_position():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "PROJECT-LINE")+ _touch(root, "JIUWENCLAW.local.md", "LOCAL-LINE")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert body.index("PROJECT-LINE") < body.index("LOCAL-LINE")+++async def test_empty_directory_no_section():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ project_sections = [+ s for s in agent.system_prompt_builder.added_sections+ if s.name == SECTION_NAME+ ]+ assert project_sections == []+++async def test_walk_up_from_subdir():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "ROOT-RULE")+ sub = root / "src" / "feature"+ sub.mkdir(parents=True)++ rail = ProjectMemoryRail(workspace=str(sub), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "ROOT-RULE" in body+++async def test_refreshes_after_file_change():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "VERSION-1")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())+ body1 = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "VERSION-1" in body1++ _touch(root, "JIUWENCLAW.md", "VERSION-2")+ await rail.before_model_call(ctx=MagicMock())+ body2 = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "VERSION-2" in body2+ assert "VERSION-1" not in body2+++async def test_ignores_legacy_runtime_files():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, ".cursorrules", "CURSOR-RULE")+ _touch(root, "AGENTS.md", "AGENTS-RULE")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ sections = [+ s for s in agent.system_prompt_builder.added_sections+ if s.name == SECTION_NAME+ ]+ assert sections == []+++async def test_reads_rules_glob_dir():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, ".jiuwen/rules/01_style.md", "STYLE-RULE")+ _touch(root, ".jiuwen/rules/02_testing.md", "TEST-RULE")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "STYLE-RULE" in body+ assert "TEST-RULE" in body+++async def test_supports_include_directives():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, ".jiuwen/rules/shared.md", "SHARED-RULE")+ _touch(+ root,+ "JIUWENCLAW.md",+ "ROOT-LINE\n@include .jiuwen/rules/shared.md\nTAIL-LINE\n",+ )++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "ROOT-LINE" in body+ assert "TAIL-LINE" in body+ assert "SHARED-RULE" in body+ assert "@include" not in body+++async def test_conditional_rule_matches_workspace_subdir():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ subdir = root / "src" / "feature"+ _touch(root, ".git/HEAD", "")+ subdir.mkdir(parents=True)+ _touch(+ root,+ ".jiuwen/rules/scoped.md",+ "---\npaths:\n - src/**\n---\nSCOPED-RULE\n",+ )++ rail = ProjectMemoryRail(workspace=str(subdir), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "SCOPED-RULE" in body+++async def test_conditional_rule_matches_inline_paths_list():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ subdir = root / "src" / "feature"+ _touch(root, ".git/HEAD", "")+ subdir.mkdir(parents=True)+ _touch(+ root,+ ".jiuwen/rules/scoped.md",+ "---\npaths: [src/**, lib/**]\n---\nINLINE-SCOPED-RULE\n",+ )++ rail = ProjectMemoryRail(workspace=str(subdir), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "INLINE-SCOPED-RULE" in body+++async def test_conditional_rule_skips_nonmatching_workspace():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ docs = root / "docs"+ _touch(root, ".git/HEAD", "")+ docs.mkdir(parents=True)+ _touch(+ root,+ ".jiuwen/rules/scoped.md",+ "---\npaths:\n - src/**\n---\nSCOPED-RULE\n",+ )++ rail = ProjectMemoryRail(workspace=str(docs), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ sections = [+ s for s in agent.system_prompt_builder.added_sections+ if s.name == SECTION_NAME+ ]+ assert sections == []+++async def test_frontmatter_stripped():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(+ root,+ "JIUWENCLAW.md",+ "---\npaths: 'src/**'\nversion: 1\n---\nBODY-ONLY\n",+ )++ rail = ProjectMemoryRail(workspace=str(root / "src"), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "BODY-ONLY" in body+ assert "paths:" not in body+ assert "version:" not in body+++async def test_frontmatter_at_end_of_file_stripped():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "---\nkey: v\n---")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ sections = [+ s for s in agent.system_prompt_builder.added_sections+ if s.name == SECTION_NAME+ ]+ assert sections == []+++async def test_uninit_clears_section():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "BEFORE-UNINIT")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())+ assert agent.system_prompt_builder.added_sections++ rail.uninit(agent)+ assert [+ s for s in agent.system_prompt_builder.added_sections+ if s.name == SECTION_NAME+ ] == []+++async def test_no_builder_is_safe():+ rail = ProjectMemoryRail(workspace="/tmp", language="en")+ agent = MagicMock()+ agent.system_prompt_builder = None+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())+++async def test_set_language_switches_active_language():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "BODY")++ rail = ProjectMemoryRail(workspace=str(root), language="cn")+ rail.set_language("en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ assert rail.get_language() == "en"+++async def test_loads_user_and_managed_rules(monkeypatch):+ with (+ tempfile.TemporaryDirectory() as td,+ tempfile.TemporaryDirectory() as user_td,+ tempfile.TemporaryDirectory() as managed_td,+ ):+ root = Path(td)+ user_root = Path(user_td)+ managed_root = Path(managed_td)+ _touch(root, ".git/HEAD", "")+ _touch(user_root, "JIUWENCLAW.md", "USER-MEMORY")+ _touch(user_root, "rules/user_rule.md", "USER-RULE")+ _touch(managed_root, "JIUWENCLAW.md", "MANAGED-MEMORY")+ _touch(managed_root, "rules/managed_rule.md", "MANAGED-RULE")++ monkeypatch.setattr(_files_mod, "USER_MEMORY_FILES", (str(user_root / "JIUWENCLAW.md"),))+ monkeypatch.setattr(_files_mod, "USER_MEMORY_GLOBS", (str(user_root / "rules" / "*.md"),))+ monkeypatch.setattr(_files_mod, "MANAGED_MEMORY_FILES", (str(managed_root / "JIUWENCLAW.md"),))+ monkeypatch.setattr(_files_mod, "MANAGED_MEMORY_GLOBS", (str(managed_root / "rules" / "*.md"),))+ _files_mod.clear_project_memory_cache()++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "USER-MEMORY" in body+ assert "USER-RULE" in body+ assert "MANAGED-MEMORY" in body+ assert "MANAGED-RULE" in body+++async def test_additional_directories_load_project_memory():+ with tempfile.TemporaryDirectory() as td, tempfile.TemporaryDirectory() as extra_td:+ root = Path(td)+ extra = Path(extra_td)+ _touch(root, ".git/HEAD", "")+ _touch(extra, "JIUWENCLAW.md", "EXTRA-PROJECT-RULE")++ rail = ProjectMemoryRail(+ workspace=str(root),+ language="en",+ additional_directories=(str(extra),),+ )+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "EXTRA-PROJECT-RULE" in body+++@dataclass+class _FakeWorkspace:+ root_path: str+++async def test_additional_directories_relative_to_workspace():+ with tempfile.TemporaryDirectory() as td:+ base = Path(td)+ root = base / "repo"+ extra = base / "shared-memory"+ _touch(root, ".git/HEAD", "")+ _touch(extra, "JIUWENCLAW.md", "RELATIVE-EXTRA-RULE")++ rail = ProjectMemoryRail(+ workspace=str(root),+ language="en",+ additional_directories=("../shared-memory",),+ )+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "RELATIVE-EXTRA-RULE" in body+++async def test_b1_parent_set_workspace_does_not_break_path_resolution():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "STILL-WORKING")++ rail = ProjectMemoryRail(workspace="/nonexistent-stub-path", language="en")+ rail.set_workspace(_FakeWorkspace(root_path=str(root))) # type: ignore[arg-type]++ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ sections = [+ s for s in agent.system_prompt_builder.added_sections+ if s.name == SECTION_NAME+ ]+ assert sections+ assert "STILL-WORKING" in sections[-1].content["en"]+++async def test_b1_no_workspace_falls_back_to_constructor_path():+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ _touch(root, ".git/HEAD", "")+ _touch(root, "JIUWENCLAW.md", "FROM-CTOR-PATH")++ rail = ProjectMemoryRail(workspace=str(root), language="en")+ assert rail.workspace is None++ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ section = agent.system_prompt_builder.added_sections[-1]+ assert "FROM-CTOR-PATH" in section.content["en"]+++async def test_nested_worktree_skips_canonical_project_but_keeps_local(monkeypatch):+ with tempfile.TemporaryDirectory() as td:+ canonical = Path(td) / "repo"+ worktree = canonical / ".jiuwen" / "worktrees" / "feature"+ _touch(canonical, ".git/HEAD", "")+ _touch(worktree, ".git/HEAD", "")+ _touch(canonical, "JIUWENCLAW.md", "CANONICAL-PROJECT")+ _touch(canonical, "JIUWENCLAW.local.md", "CANONICAL-LOCAL")+ _touch(worktree, "JIUWENCLAW.md", "WORKTREE-PROJECT")++ monkeypatch.setattr(+ _files_mod,+ "_detect_git_worktree",+ lambda _cwd: _files_mod.GitWorktreeInfo(+ worktree_root=worktree.resolve(),+ canonical_root=canonical.resolve(),+ ),+ )+ _files_mod.clear_project_memory_cache()++ rail = ProjectMemoryRail(workspace=str(worktree), language="en")+ agent = _make_agent_with_builder()+ rail.init(agent)+ await rail.before_model_call(ctx=MagicMock())++ body = agent.system_prompt_builder.added_sections[-1].content["en"]+ assert "WORKTREE-PROJECT" in body+ assert "CANONICAL-LOCAL" in body+ assert "CANONICAL-PROJECT" not in body+++async def test_after_tool_call_invalidates_cache_for_write_tools(monkeypatch):+ rail = ProjectMemoryRail(workspace="/tmp/project", language="en")+ clear_mock = MagicMock()+ monkeypatch.setattr(_rail_mod, "clear_project_memory_cache", clear_mock)++ ctx = SimpleNamespace(inputs=SimpleNamespace(tool_name="write_file"))+ await rail.after_tool_call(ctx)++ clear_mock.assert_called_once_with("/tmp/project")+++def test_resolve_workspace_path_prefers_workspace_root_path():+ rail = ProjectMemoryRail(workspace="/ctor-fallback", language="en")+ rail.set_workspace(_FakeWorkspace(root_path="/from-injection")) # type: ignore[arg-type]+ assert rail.resolve_workspace_path() == "/from-injection"+++def test_resolve_workspace_path_falls_back_when_workspace_missing():+ rail = ProjectMemoryRail(workspace="/ctor-fallback", language="en")+ assert rail.workspace is None+ assert rail.resolve_workspace_path() == "/ctor-fallback"+++def test_module_exports_project_memory_rail():+ assert hasattr(_rail_mod, "ProjectMemoryRail")diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pyindex f2e5e8ef2d..ac8569e900 100644--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -67,14 +67,16 @@ def test_resolve_skill_mode_accepts_all_and_auto_list():assert JiuWenClawDeepAdapter._resolve_skill_mode({"skill_mode": "invalid"}) == "all"-def test_build_configured_subagents_includes_optional_browser_and_configured_code_research():+# DeepAdapter only builds research_agent + browser_agent (agent mode).+# code_agent / explore_agent belong to CodeAdapter.++def test_deep_adapter_subagents_includes_optional_browser_and_configured_research():adapter = _TestableJiuWenClawDeepAdapter()adapter.set_workspace_dir("/tmp/jiuwenclaw-workspace")model = object()config = {"max_iterations": 9,"subagents": {- "code_agent": {"enabled": True, "max_iterations": 5},"research_agent": {"enabled": True},"browser_agent": {"max_iterations": 7},},@@ -83,10 +85,6 @@ def test_build_configured_subagents_includes_optional_browser_and_configured_codwith (patch.object(adapter, "_resolve_runtime_language", return_value="cn"),patch.object(adapter, "_browser_runtime_enabled", return_value=True),- patch(- "jiuwenclaw.agentserver.deep_agent.interface_deep.build_code_agent_config",- return_value="code_spec",- ) as mock_code,patch("jiuwenclaw.agentserver.deep_agent.interface_deep.build_research_agent_config",return_value="research_spec",@@ -98,14 +96,7 @@ def test_build_configured_subagents_includes_optional_browser_and_configured_cod):subagents = adapter.build_configured_subagents(model, config)- assert subagents == ["code_spec", "research_spec", "browser_spec"]- mock_code.assert_called_once_with(- model,- workspace="/tmp/jiuwenclaw-workspace",- language="cn",- rails=None,- max_iterations=5,- )+ assert subagents == ["research_spec", "browser_spec"]mock_research.assert_called_once_with(model,workspace="/tmp/jiuwenclaw-workspace",@@ -120,7 +111,7 @@ def test_build_configured_subagents_includes_optional_browser_and_configured_cod)-def test_build_configured_subagents_omits_code_research_without_explicit_enable():+def test_deep_adapter_subagents_omits_research_without_explicit_enable():adapter = _TestableJiuWenClawDeepAdapter()adapter.set_workspace_dir("/tmp/jiuwenclaw-workspace")model = object()@@ -129,10 +120,6 @@ def test_build_configured_subagents_omits_code_research_without_explicit_enable(with (patch.object(adapter, "_resolve_runtime_language", return_value="cn"),patch.object(adapter, "_browser_runtime_enabled", return_value=True),- patch(- "jiuwenclaw.agentserver.deep_agent.interface_deep.build_code_agent_config",- return_value="code_spec",- ) as mock_code,patch("jiuwenclaw.agentserver.deep_agent.interface_deep.build_research_agent_config",return_value="research_spec",@@ -144,7 +131,7 @@ def test_build_configured_subagents_omits_code_research_without_explicit_enable():subagents = adapter.build_configured_subagents(model, config)+ # DeepAdapter: no research_agent configured, browser enabledassert subagents == ["browser_spec"]- mock_code.assert_not_called()mock_research.assert_not_called()- mock_browser.assert_called_once()+ mock_browser.assert_called_once()\ No newline at end of file