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(code-rails): add CodingArtifactPostProcessRail for code-mode artifacts
NickFuryXXX66e35bc6f410
diff --git a/jiuwenswarm/agents/harness/code/rails/__init__.py b/jiuwenswarm/agents/harness/code/rails/__init__.pyindex 233b8da6d0..a0eebb3bc4 100644--- a/jiuwenswarm/agents/harness/code/rails/__init__.py+++ b/jiuwenswarm/agents/harness/code/rails/__init__.py@@ -6,8 +6,12 @@ from jiuwenswarm.agents.harness.code.rails.code_task_planning_rail import (from jiuwenswarm.agents.harness.code.rails.code_plan_approval_interrupt_rail import (PlanApprovalInterruptRail,)+from jiuwenswarm.agents.harness.code.rails.coding_artifact_post_process_rail import (+ CodingArtifactPostProcessRail,+)__all__ = [+ "CodingArtifactPostProcessRail","CodeTaskPlanningRail","PlanApprovalInterruptRail",]diff --git a/jiuwenswarm/agents/harness/code/rails/coding_artifact_post_process_rail.py b/jiuwenswarm/agents/harness/code/rails/coding_artifact_post_process_rail.pynew file mode 100644index 0000000000..45e0fe38c2--- /dev/null+++ b/jiuwenswarm/agents/harness/code/rails/coding_artifact_post_process_rail.py@@ -0,0 +1,214 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Code-mode artifact post-processing without task lifecycle ownership."""++from __future__ import annotations++import codecs+import re+import time+from pathlib import Path++from openjiuwen.core.single_agent.rail.base import (+ AgentCallbackContext,+ ToolCallInputs,+)+from openjiuwen.harness.rails.base import DeepAgentRail++from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (+ ARTIFACT_DETECTION_TOOL_NAMES,+ detect_artifact_paths,+ filter_unhooked,+ fire_artifact_hook,+ get_current_task_id,+ mark_hooked,+ pop_tool_start_time,+ resolve_workspace_base,+)+from jiuwenswarm.common.utils import logger++_COAUTHOR_HEADER = "Co-authored by OfficeAce Coding Agent"+_PYTHON_CODING_COOKIE = re.compile(r"^[ \t\f]*#.*?coding[:=][ \t]*[-\w.]+")+_HASH_COMMENT_SUFFIXES = frozenset({+ ".py", ".pyw", ".pyx", ".pxd", ".pxi",+ ".sh", ".bash", ".zsh", ".fish",+ ".rb", ".rake", ".pl", ".pm", ".r",+ ".ps1", ".psm1", ".psd1",+})+_SLASH_COMMENT_SUFFIXES = frozenset({+ ".c", ".h", ".cc", ".cpp", ".cxx", ".hpp",+ ".cs", ".java", ".js", ".jsx", ".mjs", ".cjs",+ ".ts", ".tsx", ".go", ".rs", ".swift", ".kt", ".kts",+ ".dart", ".scala", ".groovy",+})+_DASH_COMMENT_SUFFIXES = frozenset({".sql", ".lua"})+_BLOCK_COMMENT_SUFFIXES = frozenset({".css", ".scss", ".sass", ".less"})+_MARKUP_COMMENT_SUFFIXES = frozenset({".html", ".htm", ".xml", ".vue", ".svelte"})+_HASH_COMMENT_FILENAMES = frozenset({+ "dockerfile", "makefile", "rakefile", "jenkinsfile", "cmakelists.txt",+})+++def _comment_text(path: Path) -> str | None:+ suffix = path.suffix.lower()+ if suffix in _HASH_COMMENT_SUFFIXES or path.name.lower() in _HASH_COMMENT_FILENAMES:+ return f"# {_COAUTHOR_HEADER}"+ if suffix in _SLASH_COMMENT_SUFFIXES:+ return f"// {_COAUTHOR_HEADER}"+ if suffix in _DASH_COMMENT_SUFFIXES:+ return f"-- {_COAUTHOR_HEADER}"+ if suffix in _BLOCK_COMMENT_SUFFIXES:+ return f"/* {_COAUTHOR_HEADER} */"+ if suffix in _MARKUP_COMMENT_SUFFIXES:+ return f"<!-- {_COAUTHOR_HEADER} -->"+ if suffix == ".php":+ return f"// {_COAUTHOR_HEADER}"+ return None+++def _header_insert_index(path: Path, lines: list[str]) -> int:+ if not lines:+ return 0++ suffix = path.suffix.lower()+ index = 1 if lines[0].startswith("#!") else 0++ if suffix in {".py", ".pyw", ".pyx", ".pxd", ".pxi"}:+ for candidate in range(min(2, len(lines))):+ if _PYTHON_CODING_COOKIE.match(lines[candidate]):+ index = max(index, candidate + 1)+ elif suffix == ".php" and lines[0].lstrip().lower().startswith("<?php"):+ index = 1+ elif suffix in {".xml", ".html", ".htm", ".vue", ".svelte"}:+ if lines[0].lstrip().lower().startswith("<?xml"):+ index = 1++ return index+++def add_officeace_coauthor_header(path: str | Path) -> bool:+ """Add the configured OfficeAce attribution header to one code file."""+ file_path = Path(path)+ comment = _comment_text(file_path)+ if comment is None or not file_path.is_file():+ return False++ try:+ raw = file_path.read_bytes()+ has_utf8_bom = raw.startswith(codecs.BOM_UTF8)+ source = raw.decode("utf-8-sig")+ except (OSError, UnicodeDecodeError) as exc:+ logger.debug(+ "[CodingArtifactPostProcessRail] skip coauthor header path=%s error=%s",+ file_path,+ exc,+ )+ return False++ if _COAUTHOR_HEADER.casefold() in source.casefold():+ return False++ newline = "\r\n" if "\r\n" in source else "\n"+ lines = source.splitlines(keepends=True)+ index = _header_insert_index(file_path, lines)+ prefix = "".join(lines[:index])+ suffix = "".join(lines[index:])+ if prefix and not prefix.endswith(("\n", "\r")):+ prefix += newline+ updated = f"{prefix}{comment}{newline}{suffix}"+ encoded = updated.encode("utf-8")+ if has_utf8_bom:+ encoded = codecs.BOM_UTF8 + encoded++ try:+ file_path.write_bytes(encoded)+ except OSError as exc:+ logger.warning(+ "[CodingArtifactPostProcessRail] coauthor header write failed path=%s error=%s",+ file_path,+ exc,+ )+ return False+ return True+++class CodingArtifactPostProcessRail(DeepAgentRail):+ """Detect code-mode artifacts and run extension post-process hooks.++ This rail deliberately owns no todo or task-plan state. It only reuses the+ canonical artifact detection and hook helpers shared with TaskExecutionRail+ and SkillTurboArtifactRail.+ """++ priority = 85+ # The rail keeps per-invoke mutable detection state. A child agent must use+ # its own instance instead of resetting or mutating the parent's state.+ inherit_to_subagents = False++ def __init__(self, *, coauthor_header_enabled: bool = False) -> None:+ super().__init__()+ self._coauthor_header_enabled = bool(coauthor_header_enabled)+ self._tool_start_times: dict[str, float] = {}+ self._hooked_artifacts: set[tuple[str, int, int]] = set()++ async def before_invoke(self, ctx: AgentCallbackContext) -> None:+ """Reset per-invoke tool timing while retaining cross-turn deduplication."""+ self._tool_start_times = {}++ async def before_tool_call(self, ctx: AgentCallbackContext) -> None:+ if not isinstance(ctx.inputs, ToolCallInputs):+ return+ if ctx.inputs.tool_name not in ARTIFACT_DETECTION_TOOL_NAMES:+ return++ tool_call = getattr(ctx.inputs, "tool_call", None)+ tool_call_id = str(getattr(tool_call, "id", "") or "")+ if tool_call_id:+ self._tool_start_times[tool_call_id] = time.time()++ async def after_tool_call(self, ctx: AgentCallbackContext) -> None:+ if ctx.session is None or not isinstance(ctx.inputs, ToolCallInputs):+ return+ if ctx.inputs.tool_name not in ARTIFACT_DETECTION_TOOL_NAMES:+ return++ try:+ session_id = str(ctx.session.get_session_id() or "")+ except Exception:+ logger.debug(+ "[CodingArtifactPostProcessRail] failed to get session_id",+ exc_info=True,+ )+ return++ detection = detect_artifact_paths(+ ctx.inputs.tool_name,+ getattr(ctx.inputs, "tool_args", None),+ getattr(ctx.inputs, "tool_result", None),+ tool_start_time=pop_tool_start_time(self._tool_start_times, ctx),+ workspace_base=resolve_workspace_base(),+ )+ paths = filter_unhooked(detection.paths, self._hooked_artifacts)+ if not paths:+ return++ if self._coauthor_header_enabled:+ for path in paths:+ if add_officeace_coauthor_header(path):+ logger.info(+ "[CodingArtifactPostProcessRail] added coauthor header path=%s",+ path,+ )++ fired = await fire_artifact_hook(+ session_id=session_id,+ tool_name=detection.tool_name,+ task_id=get_current_task_id(),+ artifact_paths=paths,+ log_prefix="[CodingArtifactPostProcessRail]",+ )+ if fired:+ mark_hooked(paths, self._hooked_artifacts)+++__all__ = ["CodingArtifactPostProcessRail", "add_officeace_coauthor_header"]diff --git a/jiuwenswarm/common/local_env_config.py b/jiuwenswarm/common/local_env_config.pyindex 8e4a3b5d50..3c615ded3c 100644--- a/jiuwenswarm/common/local_env_config.py+++ b/jiuwenswarm/common/local_env_config.py@@ -79,6 +79,8 @@ SPAWN_ENV_KEYS: frozenset[str] = frozenset(# Unified tool switch (blacklist); config.yaml references ${DISABLED_TOOLS-...}.# Defaults to disabling search_skill / install_skill / uninstall_skill."DISABLED_TOOLS",+ # Code-mode generated-code co-author header switch; process shared.+ "JIUWENSWARM_CODE_COAUTHOR_HEADER_ENABLED",# launchEnv / config.yaml ${EXTENSION_DIRS}; process-shared (relay RELAYCLAW_SHARED_ENV_KEYS TBD)."EXTENSION_DIRS",}diff --git a/jiuwenswarm/resources/.env.template b/jiuwenswarm/resources/.env.templateindex d6bf4047c7..bde9d3647f 100644--- a/jiuwenswarm/resources/.env.template+++ b/jiuwenswarm/resources/.env.template@@ -143,6 +143,10 @@ MEMORY_MODE=# 默认禁用模型侧的技能搜索与管理工具,技能广场界面安装不受影响。DISABLED_TOOLS=search_skill,install_skill,uninstall_skill+# Add "Co-authored by OfficeAce Coding Agent" header comments to code files+# generated in Code mode. Disabled by default; restart after changing it.+JIUWENSWARM_CODE_COAUTHOR_HEADER_ENABLED=false+# WebSocket Origin validation.# Set JIUWENSWARM_ENABLE_ORIGIN_CHECK=1 to enable checks.# Use English commas only; add "none" to allow connections without an Origin header.diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 1184d4034c..0846ea5706 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -1409,6 +1409,11 @@ modes:rails:tools:code:+ artifact_post_process:+ # 为生成的代码文件添加语言对应的 header 注释:+ # "Co-authored by OfficeAce Coding Agent"。可通过 .env 开关控制,默认关闭。+ coauthor_header: ${JIUWENSWARM_CODE_COAUTHOR_HEADER_ENABLED:-false}+# 记忆开关 — 控制 CodingMemoryRail 和 ProjectMemoryRail 加载# 关闭后,coding_memory_read/write/edit 工具不可用,项目记忆文件不自动加载memory:@@ -1418,7 +1423,8 @@ modes:# 固定 Rails(以下 Rails 已在代码中固定挂载,无需在此配置):# RuntimePromptRail, ResponsePromptRail, JiuSwarmStreamEventRail, SecurityRail,# PermissionInterruptRail, SysOperationRail(FileSystemRail), LspRail,- # AgentModeRail, StructuredAskUserRail, ConfirmInterruptRail, ContextProcessorRail+ # CodingArtifactPostProcessRail, AgentModeRail, StructuredAskUserRail,+ # ConfirmInterruptRail, ContextProcessorRail# 注意:ProjectMemoryRail, CodingMemoryRail 受 memory.enabled 开关控制,# 开关关闭时不加载,开关开启时固定挂载。rails:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 43be2cb093..2036d6963a 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -58,6 +58,7 @@ from jiuwenswarm.agents.harness.code.prompt.code_prompt_builder import (build_code_system_prompt,)from jiuwenswarm.agents.harness.code.rails import (+ CodingArtifactPostProcessRail,CodeTaskPlanningRail,PlanApprovalInterruptRail,)@@ -91,6 +92,22 @@ from jiuwenswarm.common.utils import (logger = logging.getLogger(__name__)++def _parse_config_bool(value: Any, *, default: bool = False) -> bool:+ """Parse YAML and environment-backed boolean config values."""+ if value is None:+ return default+ if isinstance(value, bool):+ return value++ normalized = str(value).strip().lower()+ if normalized in {"1", "true", "yes", "on"}:+ return True+ if normalized in {"0", "false", "no", "off", ""}:+ return False+ return default++# ---------------------------------------------------------------------------# Static plan mode system prompt note (KV-cache-friendly: same content every turn)# Injected into system prompt so the model knows it's in plan mode BEFORE its@@ -360,6 +377,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):"ContextProcessorRail","ContextOverflowRecoveryRail","SysOperationRail", "CodingMemoryRail",+ "CodingArtifactPostProcessRail","AgentModeRail", "StructuredAskUserRail", "ConfirmInterruptRail","FileSystemRail", # 别名})@@ -370,6 +388,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):self._lsp_rail: LspRail | None = Noneself._project_memory_rail: ProjectMemoryRail | None = Noneself._coding_memory_rail: CodingMemoryRail | None = None+ self._coding_artifact_post_process_rail: CodingArtifactPostProcessRail | None = Noneself._worktree_rail: WorktreeRail | None = None# 单点 source-of-truth, 让 sysop_builder 的"主写入根"分支# (project_dir vs get_agent_workspace_dir) 落到 code-agent 这一支。@@ -587,6 +606,16 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):Code 模式固定包含 LspRail、ProjectMemoryRail、CodingMemoryRail。"""+ mode_config = config_base.get("modes", {}).get("code", {})+ artifact_config = mode_config.get("artifact_post_process") or {}+ coauthor_header_enabled = (+ _parse_config_bool(+ artifact_config.get("coauthor_header"),+ )+ if isinstance(artifact_config, dict)+ else False+ )+# 固定 Rails — code 模式特有rail_infos = [_RailBuildInfo("_request_summary_rail", self._build_request_summary_rail),@@ -594,6 +623,11 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):_RailBuildInfo("_response_prompt_rail", self._build_response_prompt_rail),_RailBuildInfo("_skill_retrieval_prompt_rail", self._build_skill_retrieval_prompt_rail),_RailBuildInfo("_stream_event_rail", self._build_stream_event_rail),+ _RailBuildInfo(+ "_coding_artifact_post_process_rail",+ self._build_coding_artifact_post_process_rail,+ {"coauthor_header_enabled": coauthor_header_enabled},+ ),_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),@@ -631,7 +665,6 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):# 动态 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:@@ -720,6 +753,22 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):logger.warning("[JiuwenSwarmCodeAdapter] CodeAgentModeRail create failed: %s", exc)return None+ @staticmethod+ def _build_coding_artifact_post_process_rail(+ *, coauthor_header_enabled: bool = False,+ ) -> CodingArtifactPostProcessRail | None:+ """Build code-only artifact post-processing without todo lifecycle hooks."""+ try:+ return CodingArtifactPostProcessRail(+ coauthor_header_enabled=coauthor_header_enabled,+ )+ except Exception as exc:+ logger.warning(+ "[JiuwenSwarmCodeAdapter] CodingArtifactPostProcessRail create failed: %s",+ exc,+ )+ return None+@staticmethoddef _build_code_task_planning_rail() -> CodeTaskPlanningRail | None:"""Register todo tools without openjiuwen todo system prompt injection."""diff --git a/tests/unit_tests/agentserver/rails/test_coding_artifact_post_process_rail.py b/tests/unit_tests/agentserver/rails/test_coding_artifact_post_process_rail.pynew file mode 100644index 0000000000..2dc18dda41--- /dev/null+++ b/tests/unit_tests/agentserver/rails/test_coding_artifact_post_process_rail.py@@ -0,0 +1,205 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++from types import SimpleNamespace++import pytest+from openjiuwen.core.single_agent.rail.base import ToolCallInputs++from jiuwenswarm.agents.harness.code.rails import (+ CodingArtifactPostProcessRail,+)+from jiuwenswarm.agents.harness.code.rails.coding_artifact_post_process_rail import (+ add_officeace_coauthor_header,+)+++class _FakeSession:+ def get_session_id(self) -> str:+ return "code-session"+++def _tool_ctx(path: str) -> SimpleNamespace:+ return SimpleNamespace(+ session=_FakeSession(),+ inputs=ToolCallInputs(+ tool_call=SimpleNamespace(id="tool-call-1"),+ tool_name="write_file",+ tool_args={"path": path},+ tool_result=f"Wrote {path}",+ tool_msg=None,+ ),+ )+++async def test_coding_artifact_rail_fires_hook_once_without_task_lifecycle(+ tmp_path, monkeypatch+) -> None:+ output = tmp_path / "artifact.png"+ ctx = _tool_ctx(str(output))+ rail = CodingArtifactPostProcessRail()+ calls: list[dict] = []++ async def _record_hook(**kwargs) -> bool:+ calls.append(kwargs)+ return True++ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.code.rails.coding_artifact_post_process_rail."+ "fire_artifact_hook",+ _record_hook,+ )++ await rail.before_invoke(ctx)+ await rail.before_tool_call(ctx)+ output.write_bytes(b"image")+ await rail.after_tool_call(ctx)+ await rail.after_tool_call(ctx)++ assert len(calls) == 1+ assert calls[0]["session_id"] == "code-session"+ assert calls[0]["tool_name"] == "write_file"+ assert calls[0]["artifact_paths"] == [str(output)]+ assert calls[0]["task_id"] is None+ assert not hasattr(rail, "_todo_map")+ assert not hasattr(rail, "_active_tasks")+++async def test_coding_artifact_rail_deduplicates_unchanged_file_across_invokes(+ tmp_path, monkeypatch+) -> None:+ output = tmp_path / "artifact.png"+ ctx = _tool_ctx(str(output))+ rail = CodingArtifactPostProcessRail()+ calls: list[dict] = []++ async def _record_hook(**kwargs) -> bool:+ calls.append(kwargs)+ return True++ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.code.rails.coding_artifact_post_process_rail."+ "fire_artifact_hook",+ _record_hook,+ )++ await rail.before_invoke(ctx)+ await rail.before_tool_call(ctx)+ output.write_bytes(b"unchanged-image")+ await rail.after_tool_call(ctx)++ await rail.before_invoke(ctx)+ await rail.before_tool_call(ctx)+ await rail.after_tool_call(ctx)++ assert len(calls) == 1+ assert rail._tool_start_times == {}+ assert len(rail._hooked_artifacts) == 1+++async def test_coding_artifact_rail_ignores_todo_tools(monkeypatch) -> None:+ rail = CodingArtifactPostProcessRail()+ ctx = SimpleNamespace(+ session=_FakeSession(),+ inputs=ToolCallInputs(+ tool_call=SimpleNamespace(id="todo-call-1"),+ tool_name="todo_modify",+ tool_args={"id": "1", "status": "in_progress"},+ tool_result="updated",+ tool_msg=None,+ ),+ )++ async def _unexpected_hook(**_kwargs) -> bool:+ raise AssertionError("todo tools must not trigger artifact hooks")++ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.code.rails.coding_artifact_post_process_rail."+ "fire_artifact_hook",+ _unexpected_hook,+ )++ await rail.before_tool_call(ctx)+ await rail.after_tool_call(ctx)++ assert rail._tool_start_times == {}+++def test_coauthor_header_preserves_python_shebang_cookie_and_crlf(tmp_path) -> None:+ output = tmp_path / "script.py"+ output.write_bytes(+ b"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\nprint('ok')\r\n"+ )++ assert add_officeace_coauthor_header(output)+ assert output.read_bytes() == (+ b"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n"+ b"# Co-authored by OfficeAce Coding Agent\r\nprint('ok')\r\n"+ )+ assert not add_officeace_coauthor_header(output)+++def test_coauthor_header_uses_language_comment_and_skips_non_code(tmp_path) -> None:+ typescript = tmp_path / "app.ts"+ typescript.write_text("export const value = 1;\n", encoding="utf-8")+ image = tmp_path / "image.png"+ image.write_bytes(b"image")++ assert add_officeace_coauthor_header(typescript)+ assert typescript.read_text(encoding="utf-8").startswith(+ "// Co-authored by OfficeAce Coding Agent\n"+ )+ assert not add_officeace_coauthor_header(image)+ assert image.read_bytes() == b"image"+++async def test_coauthor_header_is_disabled_by_default(tmp_path, monkeypatch) -> None:+ output = tmp_path / "artifact.py"+ ctx = _tool_ctx(str(output))+ rail = CodingArtifactPostProcessRail()++ async def _successful_hook(**_kwargs) -> bool:+ return True++ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.code.rails.coding_artifact_post_process_rail."+ "fire_artifact_hook",+ _successful_hook,+ )++ await rail.before_tool_call(ctx)+ output.write_text("print('ok')\n", encoding="utf-8")+ await rail.after_tool_call(ctx)++ assert output.read_text(encoding="utf-8") == "print('ok')\n"+++async def test_coauthor_header_enabled_for_detected_code_artifact(+ tmp_path, monkeypatch+) -> None:+ output = tmp_path / "artifact.py"+ ctx = _tool_ctx(str(output))+ rail = CodingArtifactPostProcessRail(coauthor_header_enabled=True)++ async def _successful_hook(**_kwargs) -> bool:+ return True++ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.code.rails.coding_artifact_post_process_rail."+ "fire_artifact_hook",+ _successful_hook,+ )++ await rail.before_tool_call(ctx)+ output.write_text("print('ok')\n", encoding="utf-8")+ await rail.after_tool_call(ctx)++ assert output.read_text(encoding="utf-8") == (+ "# Co-authored by OfficeAce Coding Agent\nprint('ok')\n"+ )diff --git a/tests/unit_tests/agentserver/test_code_adapter_coding_artifact_post_process_rail.py b/tests/unit_tests/agentserver/test_code_adapter_coding_artifact_post_process_rail.pynew file mode 100644index 0000000000..f1522dd1a2--- /dev/null+++ b/tests/unit_tests/agentserver/test_code_adapter_coding_artifact_post_process_rail.py@@ -0,0 +1,153 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++from unittest.mock import MagicMock++import openjiuwen.agent_evolving.trajectory as _traj_mod++if not hasattr(_traj_mod, "InMemoryTrajectoryRegistry"):+ _traj_mod.InMemoryTrajectoryRegistry = MagicMock++import jiuwenswarm.server.runtime.agent_adapter.interface_code as _ic_mod+from jiuwenswarm.common.config import resolve_env_vars+++JiuwenSwarmCodeAdapter = _ic_mod.JiuwenSwarmCodeAdapter+_FIXED_RAIL_NAMES = JiuwenSwarmCodeAdapter._FIXED_RAIL_NAMES+++def test_coding_artifact_post_process_rail_is_code_fixed_rail() -> None:+ assert "CodingArtifactPostProcessRail" in _FIXED_RAIL_NAMES+ assert "CodingArtifactPostProcessRail" not in _ic_mod._RAIL_BUILD_NAMES+++def test_code_adapter_builds_coding_artifact_post_process_rail() -> None:+ adapter = JiuwenSwarmCodeAdapter()+ captured: list = []+ real_instantiate = adapter._instantiate_rails++ def _capture(rail_infos, _config_base):+ captured.extend(rail_infos)+ return rail_infos++ object.__setattr__(adapter, "_instantiate_rails", _capture)+ try:+ adapter._build_agent_rails(config={}, config_base={}, mode="code")+ finally:+ object.__setattr__(adapter, "_instantiate_rails", real_instantiate)++ matches = [+ info for info in captured+ if info.attr_name == "_coding_artifact_post_process_rail"+ ]+ assert len(matches) == 1+ assert all(info.attr_name != "_task_execution_rail" for info in captured)+ assert (+ matches[0].build_func+ == adapter._build_coding_artifact_post_process_rail+ )+ assert matches[0].params == {"coauthor_header_enabled": False}+++def test_code_adapter_passes_enabled_coauthor_header_config() -> None:+ adapter = JiuwenSwarmCodeAdapter()+ captured: list = []+ real_instantiate = adapter._instantiate_rails++ def _capture(rail_infos, _config_base):+ captured.extend(rail_infos)+ return rail_infos++ object.__setattr__(adapter, "_instantiate_rails", _capture)+ try:+ adapter._build_agent_rails(+ config={},+ config_base={+ "modes": {+ "code": {+ "artifact_post_process": {"coauthor_header": True},+ },+ },+ },+ mode="code",+ )+ finally:+ object.__setattr__(adapter, "_instantiate_rails", real_instantiate)++ match = next(+ info for info in captured+ if info.attr_name == "_coding_artifact_post_process_rail"+ )+ assert match.params == {"coauthor_header_enabled": True}+++def test_parse_config_bool_handles_environment_strings() -> None:+ for value in ("1", "true", "TRUE", "yes", "on"):+ assert _ic_mod._parse_config_bool(value) is True++ for value in ("0", "false", "FALSE", "no", "off", ""):+ assert _ic_mod._parse_config_bool(value) is False++ assert _ic_mod._parse_config_bool("invalid") is False+++def test_coauthor_header_env_placeholder_resolves_to_strict_bool(monkeypatch) -> None:+ key = "JIUWENSWARM_CODE_COAUTHOR_HEADER_ENABLED"++ monkeypatch.setenv(key, "true")+ assert (+ _ic_mod._parse_config_bool(+ resolve_env_vars(f"${{{key}:-false}}"),+ )+ is True+ )++ monkeypatch.setenv(key, "false")+ assert (+ _ic_mod._parse_config_bool(+ resolve_env_vars(f"${{{key}:-false}}"),+ )+ is False+ )++ monkeypatch.delenv(key)+ assert (+ _ic_mod._parse_config_bool(+ resolve_env_vars(f"${{{key}:-false}}"),+ )+ is False+ )+++def test_code_adapter_treats_false_environment_string_as_disabled() -> None:+ adapter = JiuwenSwarmCodeAdapter()+ captured: list = []+ real_instantiate = adapter._instantiate_rails++ def _capture(rail_infos, _config_base):+ captured.extend(rail_infos)+ return rail_infos++ object.__setattr__(adapter, "_instantiate_rails", _capture)+ try:+ adapter._build_agent_rails(+ config={},+ config_base={+ "modes": {+ "code": {+ "artifact_post_process": {"coauthor_header": "false"},+ },+ },+ },+ mode="code",+ )+ finally:+ object.__setattr__(adapter, "_instantiate_rails", real_instantiate)++ match = next(+ info+ for info in captured+ if info.attr_name == "_coding_artifact_post_process_rail"+ )+ assert match.params == {"coauthor_header_enabled": False}diff --git a/tests/unit_tests/common/test_local_env_config.py b/tests/unit_tests/common/test_local_env_config.pyindex 08b66bc447..8ff50065c3 100644--- a/tests/unit_tests/common/test_local_env_config.py+++ b/tests/unit_tests/common/test_local_env_config.py@@ -119,6 +119,9 @@ class TestLocalEnvConfig:assert key not in SPAWN_ENV_KEYSassert is_sensitive_env_name(key) is False+ def test_code_coauthor_header_switch_is_spawn_shared(self):+ assert "JIUWENSWARM_CODE_COAUTHOR_HEADER_ENABLED" in SPAWN_ENV_KEYS+def test_export_spawn_environ_keeps_process_path_without_tenant_credentials(self):from jiuwenswarm.common.local_env_config import export_spawn_environ