JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(security-review): pre-run git and abort on failure to avoid mis-review and branch switching
ldstyle881d1c71509af
diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex c1c1d73833..b94612afc5 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -33,6 +33,7 @@ from jiuwenswarm.gateway.message_handler.evolution_approval import ()from jiuwenswarm.gateway.message_handler.prompts.review_prompt import build_review_promptfrom jiuwenswarm.gateway.message_handler.prompts.security_review_prompt import (+ GitPreExecError,build_security_review_prompt,)from jiuwenswarm.extensions.hook_event import GatewayHookEvents@@ -903,7 +904,7 @@ class MessageHandler(ABC):def _build_mode_change_notice_text(mode_label: str) -> str:return f"[收到 CLI 指令], mode 已变更为 {mode_label}"- def _handle_channel_control(self, msg: "Message") -> bool:+ async def _handle_channel_control(self, msg: "Message") -> bool:r"""处理 \new_session / \mode / \skills 指令.Returns:@@ -1209,7 +1210,27 @@ class MessageHandler(ABC):if parsed.action is ParsedControlAction.SECURITY_REVIEW_OK:extra_arg = parsed.security_review_arg or ""- security_prompt = build_security_review_prompt(extra_arg)+ cwd = (+ msg.metadata.get("cwd")+ if isinstance(msg.metadata, dict)+ else None+ )+ try:+ # 在注入阶段预执行只读 git 命令并把输出内联进 prompt;+ # 任一命令非零退出(如 origin/HEAD 未设置 / 无共同历史)即中止,+ # 不转发给 Agent。+ # 跑在 executor 里,避免 4×30s 同步 subprocess 阻塞转发循环。+ security_prompt = await asyncio.get_event_loop().run_in_executor(+ None, build_security_review_prompt, extra_arg, cwd+ )+ except GitPreExecError as exc:+ await self._send_channel_notice(+ user_infos,+ ch,+ msg.session_id,+ f"/security-review 无法执行:{exc}",+ )+ return Trueif msg.params is None:msg.params = {}msg.params["query"] = security_prompt@@ -2551,7 +2572,7 @@ class MessageHandler(ABC):# 先处理受控通道的 Channel 控制指令(如 /new_session、/mode、/skills list)- if self._handle_channel_control(msg):+ if await self._handle_channel_control(msg):# 该消息仅用于修改 session/mode,已给 Channel 回复提示,不再转发给 Agentcontinue@@ -2847,7 +2868,31 @@ class MessageHandler(ABC):continueelif parsed.action is ParsedControlAction.SECURITY_REVIEW_OK:extra_arg = parsed.security_review_arg or ""- security_prompt = build_security_review_prompt(extra_arg)+ cwd = (+ msg.metadata.get("cwd")+ if isinstance(msg.metadata, dict)+ else None+ )+ try:+ # 预执行只读 git 并内联输出;+ # 失败则发 notice 中止,不转发给 Agent。+ # 跑在 executor 里,避免 4×30s 同步 subprocess 阻塞转发循环。+ security_prompt = (+ await asyncio.get_event_loop().run_in_executor(+ None,+ build_security_review_prompt,+ extra_arg,+ cwd,+ )+ )+ except GitPreExecError as exc:+ await self._send_channel_notice(+ {"id": msg.id, "meta_data": msg.metadata},+ msg.channel_id,+ msg.session_id,+ f"/security-review 无法执行:{exc}",+ )+ continuemsg.params = dict(msg.params)msg.params["query"] = security_promptif "content" in msg.params:diff --git a/jiuwenswarm/gateway/message_handler/prompts/security_review_prompt.py b/jiuwenswarm/gateway/message_handler/prompts/security_review_prompt.pyindex d6bb214cf8..a4753c13da 100644--- a/jiuwenswarm/gateway/message_handler/prompts/security_review_prompt.py+++ b/jiuwenswarm/gateway/message_handler/prompts/security_review_prompt.py@@ -2,9 +2,52 @@from __future__ import annotations+import subprocess+from jiuwenswarm.gateway.message_handler.prompts import response_language_line-_SECURITY_REVIEW_BODY = """\++class GitPreExecError(Exception):+ """某条只读 git 命令非零退出 —— 预执行失败的中止语义。"""+++# 预执行的 4 条只读 git 命令。+# 在 prompt 构建阶段预执行、把输出内联进 prompt,任一非零退出即中止+# (git 语义:exit != 0 即 error;`git diff A...B` 有 diff 时 exit 0,+# 只在 origin/HEAD 未设置 / 无共同历史等真失败时才非零)。+_SECURITY_REVIEW_GIT_COMMANDS: list[tuple[str, list[str]]] = [+ ("GIT STATUS", ["status"]),+ ("FILES MODIFIED", ["diff", "--name-only", "origin/HEAD..."]),+ ("COMMITS", ["log", "--no-decorate", "origin/HEAD..."]),+ ("DIFF CONTENT", ["diff", "origin/HEAD..."]),+]+++def _run_security_review_git(cwd: str | None) -> dict[str, str]:+ """在 cwd 下预执行 4 条只读 git 命令;非零退出抛 :class:`GitPreExecError`。"""+ outputs: dict[str, str] = {}+ for label, args in _SECURITY_REVIEW_GIT_COMMANDS:+ cmd = ["git", "-C", cwd or "."] + args+ result = subprocess.run(+ cmd,+ capture_output=True,+ text=True,+ timeout=30,+ encoding="utf-8",+ errors="replace",+ )+ if result.returncode != 0:+ raise GitPreExecError(+ f"git {' '.join(args)} failed (exit {result.returncode}): "+ f"{result.stderr.strip()}"+ )+ outputs[label] = result.stdout+ return outputs+++# 无仓库上下文(cwd=None,如单测)时的 fallback intro:保留旧的“指令式”措辞,+# 让 LLM 自己跑 git。生产路径(message_handler 传 cwd)走 _build_inlined_intro。+_SECURITY_REVIEW_INTRO_FALLBACK = """\You are a senior security engineer conducting a focused security review of the changes on this branch.Gather context by running these git commands:@@ -14,8 +57,30 @@ Gather context by running these git commands:3. Run `git log --no-decorate origin/HEAD...` for COMMITS4. Run `git diff origin/HEAD...` for DIFF CONTENT-Review the complete diff from step 4. This contains all code changes on the current branch.-+Review the complete diff from step 4. This contains all code changes on the current branch."""+++def _build_inlined_intro(git_outputs: dict[str, str]) -> str:+ """把 4 条 git 命令的预执行输出内联成固定结构。"""+ blocks: list[str] = [+ "You are a senior security engineer conducting a focused security review "+ "of the changes on this branch.",+ "",+ ]+ for label, _ in _SECURITY_REVIEW_GIT_COMMANDS:+ blocks.append(f"{label}:")+ blocks.append("")+ blocks.append("```")+ blocks.append(git_outputs.get(label, "").rstrip())+ blocks.append("```")+ blocks.append("")+ blocks.append(+ "Review the complete diff above. This contains all code changes on the current branch."+ )+ return "\n".join(blocks)+++_SECURITY_REVIEW_BODY_TAIL = """\OBJECTIVE:Perform a security-focused code review to identify HIGH-CONFIDENCE security vulnerabilities that could have real exploitation potential. This is not a general code review - focus ONLY on security implications newly added by this PR. Do not comment on existing security concerns.@@ -175,14 +240,24 @@ Begin your analysis now. Do this in 3 steps:Your final reply must contain the markdown report and nothing else."""-def build_security_review_prompt(extra_arg: str = "") -> str:+def build_security_review_prompt(extra_arg: str = "", cwd: str | None = None) -> str:"""构建 /security-review 的 prompt。输出语言来自 config ``preferred_language``;可选 args 原样透传为附加说明。++ 当 ``cwd`` 指向仓库时,在 prompt 注入阶段**预执行** 4 条只读 git 命令+ 并把输出**内联**进 prompt(不再让 LLM 自己跑 git)。任一命令非零退出抛+ :class:`GitPreExecError`,由调用方中止本次 /security-review(不转发给 Agent)。+ ``cwd`` 为 None(如单测、无仓库上下文)时退回旧的“指令式” prompt,行为不变。"""args = extra_arg.strip() if extra_arg else ""lang_line = response_language_line()- parts = [_SECURITY_REVIEW_BODY, "", lang_line]+ if cwd is None:+ intro = _SECURITY_REVIEW_INTRO_FALLBACK+ else:+ git_outputs = _run_security_review_git(cwd) # 失败抛 GitPreExecError+ intro = _build_inlined_intro(git_outputs)+ parts = [intro, "", _SECURITY_REVIEW_BODY_TAIL, "", lang_line]if args:parts.extend(["", f"Additional instructions: {args}"])return "\n".join(parts)diff --git a/tests/unit_tests/gateway/test_message_handler_security_review_prompt.py b/tests/unit_tests/gateway/test_message_handler_security_review_prompt.pyindex 50009f6c0a..302eb95d0c 100644--- a/tests/unit_tests/gateway/test_message_handler_security_review_prompt.py+++ b/tests/unit_tests/gateway/test_message_handler_security_review_prompt.py@@ -2,12 +2,20 @@"""build_security_review_prompt 单元测试."""+import shutil+import subprocess+import pytestfrom jiuwenswarm.gateway.message_handler.prompts.security_review_prompt import (+ GitPreExecError,+ _run_security_review_git,build_security_review_prompt,)+# 用绝对路径调用 git,避免依赖 PATH 解析(G.EDV.05)。+_GIT = shutil.which("git") or "git"+@pytest.fixture(autouse=True)def _english_config(monkeypatch: pytest.MonkeyPatch) -> None:@@ -18,6 +26,7 @@ def _english_config(monkeypatch: pytest.MonkeyPatch) -> None:def test_build_security_review_prompt_runs_git_commands_in_english() -> None:+ # cwd=None → 旧的“指令式” prompt(让 LLM 自己跑 git),行为不变。prompt = build_security_review_prompt("")assert "`git status`" in promptassert "`git diff --name-only origin/HEAD...`" in prompt@@ -45,3 +54,88 @@ def test_build_security_review_prompt_chinese_from_config()prompt = build_security_review_prompt("")assert "Respond in Chinese (simplified)." in prompt+++# ---- cwd 启用预执行 + 失败中止 ----+++def _make_repo(path: str) -> None:+ """建一个带 origin/HEAD 指向的本地 git 仓库(用本地 bare 仓库当 origin)。"""+ subprocess.run([_GIT, "init", "-q", path], check=True)+ subprocess.run([_GIT, "-C", path, "config", "user.email", "[email protected]"], check=True)+ subprocess.run([_GIT, "-C", path, "config", "user.name", "t"], check=True)+ subprocess.run([_GIT, "-C", path, "config", "commit.gpgsign", "false"], check=True)+ subprocess.run([_GIT, "-C", path, "commit", "--allow-empty", "-m", "init", "-q"], check=True)+++def _add_origin_head(path: str, bare: str) -> None:+ """给仓库加一个 origin 远端(本地 bare)并把 HEAD 设上去。++ bare 仓库路径由调用方提供(建议放在 pytest 的 tmp_path 下,由其自动清理,+ 避免 tempfile.mkdtemp 泄漏临时目录)。+ """+ subprocess.run([_GIT, "init", "--bare", "-q", bare], check=True)+ subprocess.run([_GIT, "-C", path, "remote", "add", "origin", bare], check=True)+ subprocess.run([_GIT, "-C", path, "push", "-q", "origin", "HEAD"], check=True)+ # 先 fetch 建立 refs/remotes/origin/* ,再用显式分支名 set-head+ # (`set-head origin HEAD` 在某些 git 版本会静默不写 symref)。+ subprocess.run([_GIT, "-C", path, "fetch", "-q", "origin"], check=True)+ subprocess.run([_GIT, "-C", path, "remote", "set-head", "origin", "master"], check=True)+++def test_run_security_review_git_succeeds_when_origin_head_set(tmp_path):+ repo = str(tmp_path / "repo")+ _make_repo(repo)+ _add_origin_head(repo, str(tmp_path / "bare"))+ # 当前分支无改动:4 条命令仍应 exit 0(git diff A...B 有/无 diff 都 exit 0)。+ out = _run_security_review_git(repo)+ assert set(out) == {"GIT STATUS", "FILES MODIFIED", "COMMITS", "DIFF CONTENT"}+++def test_run_security_review_git_aborts_without_origin_head(tmp_path):+ repo = str(tmp_path / "repo")+ _make_repo(repo)+ # 不设 origin/HEAD → git diff origin/HEAD... exit 128 → 预执行中止。+ with pytest.raises(GitPreExecError):+ _run_security_review_git(repo)+++def test_build_security_review_prompt_inlines_git_outputs(tmp_path):+ repo = str(tmp_path / "repo")+ _make_repo(repo)+ _add_origin_head(repo, str(tmp_path / "bare"))+ # 制造一个改动,让 DIFF CONTENT 非空。+ (tmp_path / "repo" / "f.txt").write_text("hello\n")+ subprocess.run([_GIT, "-C", repo, "add", "f.txt"], check=True)+ subprocess.run([_GIT, "-C", repo, "commit", "-m", "add f", "-q"], check=True)++ prompt = build_security_review_prompt("", cwd=repo)+ # 内联段落存在+ assert "GIT STATUS:" in prompt+ assert "FILES MODIFIED:" in prompt+ assert "COMMITS:" in prompt+ assert "DIFF CONTENT:" in prompt+ # 不再让 LLM 自己跑 git(输出已内联)+ assert "Run `git status`" not in prompt+ # diff 内容已内联+ assert "hello" in prompt+ # 仍带语言行与分析正文+ assert "Respond in English." in prompt+ assert "FALSE POSITIVE FILTERING" in prompt+++def test_build_security_review_prompt_aborts_on_git_failure(tmp_path):+ repo = str(tmp_path / "repo")+ _make_repo(repo)+ # 无 origin/HEAD → 预执行抛错,prompt 不会被构建。+ with pytest.raises(GitPreExecError):+ build_security_review_prompt("", cwd=repo)+++def test_build_security_review_prompt_inlined_passes_through_args(tmp_path):+ repo = str(tmp_path / "repo")+ _make_repo(repo)+ _add_origin_head(repo, str(tmp_path / "bare"))+ prompt = build_security_review_prompt("focus on auth bypass", cwd=repo)+ assert prompt.rstrip().endswith("Additional instructions: focus on auth bypass")+ assert "GIT STATUS:" in prompt