Skip to content

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(review): add /review slash command for local PR review and add /security-review slash command for branch security audit

ldstyle8eee0949acc38
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.ts
index d9fb83a7a9..7d079fe71c 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/help.ts
@@ -4,7 +4,7 @@ import { makeItem } from "../helpers.js";
const COMMAND_GROUPS: Record<string, { name: string; commands: string[] }> = {
core: {
name: "Core",
- commands: ["help", "clear", "exit", "init", "simplify", "copy", "export"],
+ commands: ["help", "clear", "exit", "init", "simplify", "copy", "export", "review", "security-review"],
},
session: {
name: "Session",
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/review.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/review.ts
new file mode 100644
index 0000000000..78b8f890fb
--- /dev/null
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/review.ts
@@ -0,0 +1,31 @@
+import { makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+/**
+ * /review - Review a pull request locally in your current session.
+ * Usage: /review [PR number or URL]
+ *
+ * Sends the raw /review command to the backend. The backend parses it,
+ * builds the review prompt via build_review_prompt, and
+ * forwards it to the Agent. This keeps a single source of truth for the
+ * review prompt template.
+ */
+export function createReviewCommand(): SlashCommand {
+ return {
+ name: "review",
+ description: "Review a pull request locally in your current session",
+ usage: "/review [PR number or URL]",
+ example: "/review 123",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: (ctx, args) => {
+ const command = args.trim() ? `/review ${args.trim()}` : "/review";
+ const requestId = ctx.sendMessage(command);
+ if (!requestId) {
+ ctx.addItem(
+ makeItem(ctx.sessionId, "error", "offline: waiting for reconnect before sending review request"),
+ );
+ }
+ },
+ };
+}
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/security-review.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/security-review.ts
new file mode 100644
index 0000000000..8bc2ea0b90
--- /dev/null
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/security-review.ts
@@ -0,0 +1,38 @@
+import { makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+/**
+ * /security-review - Security review of pending changes on the current branch.
+ * Usage: /security-review [optional focus instructions]
+ *
+ * Sends the raw /security-review command to the backend. The backend parses it,
+ * builds the security review prompt via build_security_review_prompt, and
+ * forwards it to the Agent. This keeps a single source of truth for the
+ * security review prompt template.
+ */
+export function createSecurityReviewCommand(): SlashCommand {
+ return {
+ name: "security-review",
+ description:
+ "Complete a security review of the pending changes on the current branch",
+ usage: "/security-review [optional focus instructions]",
+ example: "/security-review",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: (ctx, args) => {
+ const command = args.trim()
+ ? `/security-review ${args.trim()}`
+ : "/security-review";
+ const requestId = ctx.sendMessage(command);
+ if (!requestId) {
+ ctx.addItem(
+ makeItem(
+ ctx.sessionId,
+ "error",
+ "offline: waiting for reconnect before sending security review request",
+ ),
+ );
+ }
+ },
+ };
+}
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
index 0cf6c984c3..f57a54bf0f 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
@@ -46,6 +46,8 @@ import { createAutoHarnessCommand } from "./builtins/auto-harness.js";
import { createThemeCommand } from "./builtins/theme.js";
import { createWorkspaceCommand } from "./builtins/workspace-dir.js";
import { createUsageCommand } from "./builtins/usage.js";
+import { createReviewCommand } from "./builtins/review.js";
+import { createSecurityReviewCommand } from "./builtins/security-review.js";
export function createBuiltinCommands(): SlashCommand[] {
const commands: SlashCommand[] = [
@@ -90,6 +92,8 @@ export function createBuiltinCommands(): SlashCommand[] {
createThemeCommand(),
createWorkspaceCommand(),
createUsageCommand(),
+ createReviewCommand(),
+ createSecurityReviewCommand(),
createMemoryCommand(),
createPluginCommand(),
createReloadPluginsCommand(),
diff --git a/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py b/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py
index a027fb9d19..1cf7e8b457 100644
--- a/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py
+++ b/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py
@@ -28,6 +28,8 @@ class GatewaySlashCommand(str, Enum):
SKILLS_LIST = "/skills list"
BRANCH = "/branch"
REWIND = "/rewind"
+ REVIEW = "/review"
+ SECURITY_REVIEW = "/security-review"
class ModeSubcommand(str, Enum):
@@ -89,6 +91,10 @@ class ParsedControlAction(str, Enum):
REWIND_BAD = "rewind_bad"
REWIND_CONFIRM = "rewind_confirm"
REWIND_CANCEL = "rewind_cancel"
+ REVIEW_OK = "review_ok"
+ REVIEW_BAD = "review_bad"
+ SECURITY_REVIEW_OK = "security_review_ok"
+ SECURITY_REVIEW_BAD = "security_review_bad"
@dataclass(frozen=True)
@@ -106,6 +112,24 @@ class ParsedChannelControl:
"""rewind_ok 时为用户指定的回退轮次编号;None 表示未指定。"""
rewind_pending_turn: int | None = None
"""rewind_ok 时记录原始轮次编号,用于 confirm/cancel 两步确认。"""
+ pr_arg: str | None = None
+ """review_ok 时为用户指定的 PR 编号、URL 或自由文本;空字符串表示未指定,将展示 PR 列表。"""
+ security_review_arg: str | None = None
+ """security_review_ok 时为用户可选附加说明;空字符串表示未指定。"""
+
+
+_PR_ARG_MAX_LEN = 2048
+
+
+def _sanitize_pr_arg(arg: str) -> str | None:
+ """Pass-through /review args; reject only unsafe control chars or length."""
+ if not arg:
+ return ""
+ if len(arg) > _PR_ARG_MAX_LEN:
+ return None
+ if any(ord(ch) < 32 for ch in arg):
+ return None
+ return arg
def parse_channel_control_text(text: str) -> ParsedChannelControl:
@@ -120,6 +144,10 @@ def parse_channel_control_text(text: str) -> ParsedChannelControl:
- /rewind [N] 合法;N 为可选回退轮次编号(正整数);无参数或非整数参数为非法。
- /rewind confirm N 确认执行之前发起的 /rewind N。
- /rewind cancel 取消之前发起的 /rewind N。
+ - /review [args] 合法;args 原样透传;无参数展示 PR 列表;
+ 过长或含控制字符为非法。
+ - /security-review [args] 合法;args 原样透传;无参数审查当前分支变更;
+ 过长或含控制字符为非法。
"""
if not text:
return ParsedChannelControl(ParsedControlAction.NONE)
@@ -176,6 +204,32 @@ def parse_channel_control_text(text: str) -> ParsedChannelControl:
return ParsedChannelControl(ParsedControlAction.REWIND_OK, rewind_turn=turn)
except (ValueError, TypeError):
return ParsedChannelControl(ParsedControlAction.REWIND_BAD)
+ if t == GatewaySlashCommand.SECURITY_REVIEW.value:
+ return ParsedChannelControl(
+ ParsedControlAction.SECURITY_REVIEW_OK, security_review_arg=""
+ )
+ if t.startswith(f"{GatewaySlashCommand.SECURITY_REVIEW.value} "):
+ arg = t[len(GatewaySlashCommand.SECURITY_REVIEW.value):].strip()
+ if not arg:
+ return ParsedChannelControl(
+ ParsedControlAction.SECURITY_REVIEW_OK, security_review_arg=""
+ )
+ sanitized = _sanitize_pr_arg(arg)
+ if sanitized is None:
+ return ParsedChannelControl(ParsedControlAction.SECURITY_REVIEW_BAD)
+ return ParsedChannelControl(
+ ParsedControlAction.SECURITY_REVIEW_OK, security_review_arg=sanitized
+ )
+ if t == GatewaySlashCommand.REVIEW.value:
+ return ParsedChannelControl(ParsedControlAction.REVIEW_OK, pr_arg="")
+ if t.startswith(f"{GatewaySlashCommand.REVIEW.value} "):
+ arg = t[len(GatewaySlashCommand.REVIEW.value):].strip()
+ if not arg:
+ return ParsedChannelControl(ParsedControlAction.REVIEW_OK, pr_arg="")
+ sanitized = _sanitize_pr_arg(arg)
+ if sanitized is None:
+ return ParsedChannelControl(ParsedControlAction.REVIEW_BAD)
+ return ParsedChannelControl(ParsedControlAction.REVIEW_OK, pr_arg=sanitized)
return ParsedChannelControl(ParsedControlAction.NONE)
@@ -206,6 +260,10 @@ def is_control_like_for_im_batching(text: str) -> bool:
return True
if t.startswith(GatewaySlashCommand.REWIND.value):
return True
+ if t.startswith(GatewaySlashCommand.REVIEW.value):
+ return True
+ if t.startswith(GatewaySlashCommand.SECURITY_REVIEW.value):
+ return True
return False
@@ -298,6 +356,22 @@ FIRST_BATCH_REGISTRY: tuple[SlashCommandEntry, ...] = (
req_method="agents.list",
notes="TUI agent 配置管理菜单;TUI 通过 agents.* 方法与后端交互。",
),
+ SlashCommandEntry(
+ id="review",
+ canonical_text=f"{GatewaySlashCommand.REVIEW.value} [args]",
+ scope="gateway",
+ req_method=None,
+ notes="受控通道代码审查:args 透传注入 prompt,"
+ "由 Agent 执行 gh pr list/view/diff;无 git/gh 预检。",
+ ),
+ SlashCommandEntry(
+ id="security-review",
+ canonical_text=f"{GatewaySlashCommand.SECURITY_REVIEW.value} [args]",
+ scope="gateway",
+ req_method=None,
+ notes="受控通道安全审查:args 透传注入 prompt,"
+ "由 Agent 执行 git status/diff/log 并做安全分析;无 git 预检。",
+ ),
)
diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.py
index cdb05402e1..8f108365f8 100644
--- a/jiuwenswarm/gateway/message_handler/message_handler.py
+++ b/jiuwenswarm/gateway/message_handler/message_handler.py
@@ -22,6 +22,10 @@ from jiuwenswarm.gateway.message_handler.command_parser.slash_command import (
ParsedControlAction,
parse_channel_control_text,
)
+from jiuwenswarm.gateway.message_handler.prompts.review_prompt import build_review_prompt
+from jiuwenswarm.gateway.message_handler.prompts.security_review_prompt import (
+ build_security_review_prompt,
+)
from jiuwenswarm.extensions.hook_event import GatewayHookEvents
from jiuwenswarm.extensions.hooks_context import GatewayChatHookContext
from jiuwenswarm.common.hooks_config import load_hooks_config
@@ -1126,6 +1130,55 @@ class MessageHandler(ABC):
)
return True
+ if parsed.action is ParsedControlAction.REVIEW_BAD:
+ asyncio.create_task(
+ self._send_channel_notice(
+ user_infos,
+ ch,
+ msg.session_id,
+ "非法指令,/review 参数过长或含有非法控制字符",
+ )
+ )
+ return True
+
+ if parsed.action is ParsedControlAction.REVIEW_OK:
+ # /review [args]:注入 review prompt,转发 Agent 执行 gh pr list/view/diff 并分析
+ pr_arg = parsed.pr_arg or ""
+ review_prompt = build_review_prompt(pr_arg)
+ if msg.params is None:
+ msg.params = {}
+ msg.params["query"] = review_prompt
+ logger.info(
+ "[MessageHandler] /review prompt injected channel=%s pr_arg=%s",
+ channel_type,
+ pr_arg or "<none>",
+ )
+ return False # 继续转发给 AgentServer,让 Agent 执行审查
+
+ if parsed.action is ParsedControlAction.SECURITY_REVIEW_BAD:
+ asyncio.create_task(
+ self._send_channel_notice(
+ user_infos,
+ ch,
+ msg.session_id,
+ "非法指令,/security-review 参数过长或含有非法控制字符",
+ )
+ )
+ return True
+
+ if parsed.action is ParsedControlAction.SECURITY_REVIEW_OK:
+ extra_arg = parsed.security_review_arg or ""
+ security_prompt = build_security_review_prompt(extra_arg)
+ if msg.params is None:
+ msg.params = {}
+ msg.params["query"] = security_prompt
+ logger.info(
+ "[MessageHandler] /security-review prompt injected channel=%s extra_arg=%s",
+ channel_type,
+ extra_arg or "<none>",
+ )
+ return False
+
return False
async def _skills_slash_notice(
@@ -2856,6 +2909,58 @@ class MessageHandler(ABC):
content = msg.params.get("query") or msg.params.get("content") or ""
attachments = msg.params.get("attachments")
if isinstance(content, str):
+ # ---- Resolve /review and /security-review slash commands (all channels) ----
+ stripped = content.strip()
+ if stripped:
+ parsed = parse_channel_control_text(stripped)
+ if parsed.action is ParsedControlAction.REVIEW_BAD:
+ asyncio.create_task(
+ self._send_channel_notice(
+ {"id": msg.id, "meta_data": msg.metadata},
+ msg.channel_id,
+ msg.session_id,
+ "非法指令,/review 参数过长或含有非法控制字符",
+ )
+ )
+ continue
+ if parsed.action is ParsedControlAction.REVIEW_OK:
+ pr_arg = parsed.pr_arg or ""
+ review_prompt = build_review_prompt(pr_arg)
+ msg.params = dict(msg.params)
+ msg.params["query"] = review_prompt
+ if "content" in msg.params:
+ msg.params["content"] = review_prompt
+ content = review_prompt
+ logger.info(
+ "[MessageHandler] /review prompt injected for chat.send channel=%s pr_arg=%s",
+ getattr(msg, "channel_id", ""),
+ pr_arg or "<none>",
+ )
+ elif parsed.action is ParsedControlAction.SECURITY_REVIEW_BAD:
+ asyncio.create_task(
+ self._send_channel_notice(
+ {"id": msg.id, "meta_data": msg.metadata},
+ msg.channel_id,
+ msg.session_id,
+ "非法指令,/security-review 参数过长或含有非法控制字符",
+ )
+ )
+ continue
+ elif parsed.action is ParsedControlAction.SECURITY_REVIEW_OK:
+ extra_arg = parsed.security_review_arg or ""
+ security_prompt = build_security_review_prompt(extra_arg)
+ msg.params = dict(msg.params)
+ msg.params["query"] = security_prompt
+ if "content" in msg.params:
+ msg.params["content"] = security_prompt
+ content = security_prompt
+ logger.info(
+ "[MessageHandler] /security-review prompt injected "
+ "for chat.send channel=%s extra_arg=%s",
+ getattr(msg, "channel_id", ""),
+ extra_arg or "<none>",
+ )
+
cwd = None
if isinstance(msg.metadata, dict):
cwd = msg.metadata.get("cwd")
diff --git a/jiuwenswarm/gateway/message_handler/prompts/__init__.py b/jiuwenswarm/gateway/message_handler/prompts/__init__.py
new file mode 100644
index 0000000000..73be1b88e6
--- /dev/null
+++ b/jiuwenswarm/gateway/message_handler/prompts/__init__.py
@@ -0,0 +1,11 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from jiuwenswarm.common.config import get_config
+
+
+def response_language_line() -> str:
+ """根据 config.yaml ``preferred_language`` 生成 Agent 回复语言指令。"""
+ lang = str(get_config().get("preferred_language") or "zh").strip().lower()
+ if lang != "en":
+ lang = "zh"
+ return "Respond in Chinese (simplified)." if lang == "zh" else "Respond in English."
diff --git a/jiuwenswarm/gateway/message_handler/prompts/review_prompt.py b/jiuwenswarm/gateway/message_handler/prompts/review_prompt.py
new file mode 100644
index 0000000000..a0061a1eb9
--- /dev/null
+++ b/jiuwenswarm/gateway/message_handler/prompts/review_prompt.py
@@ -0,0 +1,39 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Claude Code ``LOCAL_REVIEW_PROMPT`` 对齐的 PR 审查 prompt(单一数据源)."""
+
+from __future__ import annotations
+
+from jiuwenswarm.gateway.message_handler.prompts import response_language_line
+
+
+def build_review_prompt(pr_arg: str) -> str:
+ """构建 /review 的 prompt,指示 Agent 使用 gh CLI 审查 PR。
+
+ gh-only、args 原样透传、始终包含 ``PR number:`` 行;无 git/gh 预检。
+ 输出语言来自 config ``preferred_language``。
+ """
+ args = pr_arg.strip() if pr_arg else ""
+ lang_line = response_language_line()
+ return f"""You are an expert code reviewer. Follow these steps:
+
+1. If no PR number is provided in the args, run `gh pr list` to show open PRs
+2. If a PR number is provided, run `gh pr view <number>` to get PR details
+3. Run `gh pr diff <number>` to get the diff
+4. Analyze the changes and provide a thorough code review that includes:
+ - Overview of what the PR does
+ - Analysis of code quality and style
+ - Specific suggestions for improvements
+ - Any potential issues or risks
+
+Keep your review concise but thorough. Focus on:
+- Code correctness
+- Following project conventions
+- Performance implications
+- Test coverage
+- Security considerations
+
+Format your review with clear sections and bullet points.
+
+{lang_line}
+PR number: {args}"""
diff --git a/jiuwenswarm/gateway/message_handler/prompts/security_review_prompt.py b/jiuwenswarm/gateway/message_handler/prompts/security_review_prompt.py
new file mode 100644
index 0000000000..d6bb214cf8
--- /dev/null
+++ b/jiuwenswarm/gateway/message_handler/prompts/security_review_prompt.py
@@ -0,0 +1,188 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from __future__ import annotations
+
+from jiuwenswarm.gateway.message_handler.prompts import response_language_line
+
+_SECURITY_REVIEW_BODY = """\
+You are a senior security engineer conducting a focused security review of the changes on this branch.
+
+Gather context by running these git commands:
+
+1. Run `git status` for GIT STATUS
+2. Run `git diff --name-only origin/HEAD...` for FILES MODIFIED
+3. Run `git log --no-decorate origin/HEAD...` for COMMITS
+4. Run `git diff origin/HEAD...` for DIFF CONTENT
+
+Review the complete diff from step 4. This contains all code changes on the current branch.
+
+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.
+
+CRITICAL INSTRUCTIONS:
+1. MINIMIZE FALSE POSITIVES: Only flag issues where you're >80% confident of actual exploitability
+2. AVOID NOISE: Skip theoretical issues, style concerns, or low-impact findings
+3. FOCUS ON IMPACT: Prioritize vulnerabilities that could lead to unauthorized access, data breaches, or system compromise
+4. EXCLUSIONS: Do NOT report the following issue types:
+ - Denial of Service (DOS) vulnerabilities, even if they allow service disruption
+ - Secrets or sensitive data stored on disk (these are handled by other processes)
+ - Rate limiting or resource exhaustion issues
+
+SECURITY CATEGORIES TO EXAMINE:
+
+**Input Validation Vulnerabilities:**
+- SQL injection via unsanitized user input
+- Command injection in system calls or subprocesses
+- XXE injection in XML parsing
+- Template injection in templating engines
+- NoSQL injection in database queries
+- Path traversal in file operations
+
+**Authentication & Authorization Issues:**
+- Authentication bypass logic
+- Privilege escalation paths
+- Session management flaws
+- JWT token vulnerabilities
+- Authorization logic bypasses
+
+**Crypto & Secrets Management:**
+- Hardcoded API keys, passwords, or tokens
+- Weak cryptographic algorithms or implementations
+- Improper key storage or management
+- Cryptographic randomness issues
+- Certificate validation bypasses
+
+**Injection & Code Execution:**
+- Remote code execution via deseralization
+- Pickle injection in Python
+- YAML deserialization vulnerabilities
+- Eval injection in dynamic code execution
+- XSS vulnerabilities in web applications (reflected, stored, DOM-based)
+
+**Data Exposure:**
+- Sensitive data logging or storage
+- PII handling violations
+- API endpoint data leakage
+- Debug information exposure
+
+Additional notes:
+- Even if something is only exploitable from the local network, it can still be a HIGH severity issue
+
+ANALYSIS METHODOLOGY:
+
+Phase 1 - Repository Context Research (Use file search tools):
+- Identify existing security frameworks and libraries in use
+- Look for established secure coding patterns in the codebase
+- Examine existing sanitization and validation patterns
+- Understand the project's security model and threat model
+
+Phase 2 - Comparative Analysis:
+- Compare new code changes against existing security patterns
+- Identify deviations from established secure practices
+- Look for inconsistent security implementations
+- Flag code that introduces new attack surfaces
+
+Phase 3 - Vulnerability Assessment:
+- Examine each modified file for security implications
+- Trace data flow from user inputs to sensitive operations
+- Look for privilege boundaries being crossed unsafely
+- Identify injection points and unsafe deserialization
+
+REQUIRED OUTPUT FORMAT:
+
+You MUST output your findings in markdown. The markdown output should contain the file, line number, severity, category (e.g. `sql_injection` or `xss`), description, exploit scenario, and fix recommendation.
+
+For example:
+
+# Vuln 1: XSS: `foo.py:42`
+
+* Severity: High
+* Description: User input from `username` parameter is directly interpolated into HTML without escaping, allowing reflected XSS attacks
+* Exploit Scenario: Attacker crafts URL like /bar?q=<script>alert(document.cookie)</script> to execute JavaScript in victim's browser, enabling session hijacking or data theft
+* Recommendation: Use Flask's escape() function or Jinja2 templates with auto-escaping enabled for all user inputs rendered in HTML
+
+SEVERITY GUIDELINES:
+- **HIGH**: Directly exploitable vulnerabilities leading to RCE, data breach, or authentication bypass
+- **MEDIUM**: Vulnerabilities requiring specific conditions but with significant impact
+- **LOW**: Defense-in-depth issues or lower-impact vulnerabilities
+
+CONFIDENCE SCORING:
+- 0.9-1.0: Certain exploit path identified, tested if possible
+- 0.8-0.9: Clear vulnerability pattern with known exploitation methods
+- 0.7-0.8: Suspicious pattern requiring specific conditions to exploit
+- Below 0.7: Don't report (too speculative)
+
+FINAL REMINDER:
+Focus on HIGH and MEDIUM findings only. Better to miss some theoretical issues than flood the report with false positives. Each finding should be something a security engineer would confidently raise in a PR review.
+
+FALSE POSITIVE FILTERING:
+
+> You do not need to run commands to reproduce the vulnerability, just read the code to determine if it is a real vulnerability. Do not use the bash tool or write to any files.
+>
+> HARD EXCLUSIONS - Automatically exclude findings matching these patterns:
+> 1. Denial of Service (DOS) vulnerabilities or resource exhaustion attacks.
+> 2. Secrets or credentials stored on disk if they are otherwise secured.
+> 3. Rate limiting concerns or service overload scenarios.
+> 4. Memory consumption or CPU exhaustion issues.
+> 5. Lack of input validation on non-security-critical fields without proven security impact.
+> 6. Input sanitization concerns for GitHub Action workflows unless they are clearly triggerable via untrusted input.
+> 7. A lack of hardening measures. Code is not expected to implement all security best practices, only flag concrete vulnerabilities.
+> 8. Race conditions or timing attacks that are theoretical rather than practical issues. Only report a race condition if it is concretely problematic.
+> 9. Vulnerabilities related to outdated third-party libraries. These are managed separately and should not be reported here.
+> 10. Memory safety issues such as buffer overflows or use-after-free-vulnerabilities are impossible in rust. Do not report memory safety issues in rust or any other memory safe languages.
+> 11. Files that are only unit tests or only used as part of running tests.
+> 12. Log spoofing concerns. Outputting un-sanitized user input to logs is not a vulnerability.
+> 13. SSRF vulnerabilities that only control the path. SSRF is only a concern if it can control the host or protocol.
+> 14. Including user-controlled content in AI system prompts is not a vulnerability.
+> 15. Regex injection. Injecting untrusted content into a regex is not a vulnerability.
+> 16. Regex DOS concerns.
+> 16. Insecure documentation. Do not report any findings in documentation files such as markdown files.
+> 17. A lack of audit logs is not a vulnerability.
+>
+> PRECEDENTS -
+> 1. Logging high value secrets in plaintext is a vulnerability. Logging URLs is assumed to be safe.
+> 2. UUIDs can be assumed to be unguessable and do not need to be validated.
+> 3. Environment variables and CLI flags are trusted values. Attackers are generally not able to modify them in a secure environment. Any attack that relies on controlling an environment variable is invalid.
+> 4. Resource management issues such as memory or file descriptor leaks are not valid.
+> 5. Subtle or low impact web vulnerabilities such as tabnabbing, XS-Leaks, prototype pollution, and open redirects should not be reported unless they are extremely high confidence.
+> 6. React and Angular are generally secure against XSS. These frameworks do not need to sanitize or escape user input unless it is using dangerouslySetInnerHTML, bypassSecurityTrustHtml, or similar methods. Do not report XSS vulnerabilities in React or Angular components or tsx files unless they are using unsafe methods.
+> 7. Most vulnerabilities in github action workflows are not exploitable in practice. Before validating a github action workflow vulnerability ensure it is concrete and has a very specific attack path.
+> 8. A lack of permission checking or authentication in client-side JS/TS code is not a vulnerability. Client-side code is not trusted and does not need to implement these checks, they are handled on the server-side. The same applies to all flows that send untrusted data to the backend, the backend is responsible for validating and sanitizing all inputs.
+> 9. Only include MEDIUM findings if they are obvious and concrete issues.
+> 10. Most vulnerabilities in ipython notebooks (*.ipynb files) are not exploitable in practice. Before validating a notebook vulnerability ensure it is concrete and has a very specific attack path where untrusted input can trigger the vulnerability.
+> 11. Logging non-PII data is not a vulnerability even if the data may be sensitive. Only report logging vulnerabilities if they expose sensitive information such as secrets, passwords, or personally identifiable information (PII).
+> 12. Command injection vulnerabilities in shell scripts are generally not exploitable in practice since shell scripts generally do not run with untrusted user input. Only report command injection vulnerabilities in shell scripts if they are concrete and have a very specific attack path for untrusted input.
+>
+> SIGNAL QUALITY CRITERIA - For remaining findings, assess:
+> 1. Is there a concrete, exploitable vulnerability with a clear attack path?
+> 2. Does this represent a real security risk vs theoretical best practice?
+> 3. Are there specific code locations and reproduction steps?
+> 4. Would this finding be actionable for a security team?
+>
+> For each finding, assign a confidence score from 1-10:
+> - 1-3: Low confidence, likely false positive or noise
+> - 4-6: Medium confidence, needs investigation
+> - 7-10: High confidence, likely true vulnerability
+
+START ANALYSIS:
+
+Begin your analysis now. Do this in 3 steps:
+
+1. Use a sub-task to identify vulnerabilities. Use the repository exploration tools to understand the codebase context, then analyze the PR changes for security implications. In the prompt for this sub-task, include all of the above.
+2. Then for each vulnerability identified by the above sub-task, create a new sub-task to filter out false-positives. Launch these sub-tasks as parallel sub-tasks. In the prompt for these sub-tasks, include everything in the "FALSE POSITIVE FILTERING" instructions.
+3. Filter out any vulnerabilities where the sub-task reported a confidence less than 8.
+
+Your final reply must contain the markdown report and nothing else."""
+
+
+def build_security_review_prompt(extra_arg: str = "") -> str:
+ """构建 /security-review 的 prompt。
+
+ 输出语言来自 config ``preferred_language``;可选 args 原样透传为附加说明。
+ """
+ args = extra_arg.strip() if extra_arg else ""
+ lang_line = response_language_line()
+ parts = [_SECURITY_REVIEW_BODY, "", lang_line]
+ if args:
+ parts.extend(["", f"Additional instructions: {args}"])
+ return "\n".join(parts)
diff --git a/tests/unit_tests/gateway/test_message_handler_review_prompt.py b/tests/unit_tests/gateway/test_message_handler_review_prompt.py
new file mode 100644
index 0000000000..7b0f971349
--- /dev/null
+++ b/tests/unit_tests/gateway/test_message_handler_review_prompt.py
@@ -0,0 +1,43 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""build_review_prompt 单元测试."""
+
+import pytest
+
+from jiuwenswarm.gateway.message_handler.prompts.review_prompt import build_review_prompt
+
+
[email protected](autouse=True)
+def _english_config(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.message_handler.prompts.get_config",
+ lambda: {"preferred_language": "en"},
+ )
+
+
+def test_build_review_prompt_empty_args_lists_prs_in_english() -> None:
+ prompt = build_review_prompt("")
+ assert "`gh pr list`" in prompt
+ assert "`gh pr view <number>`" in prompt
+ assert "`gh pr diff <number>`" in prompt
+ assert "PR number: " in prompt
+ assert prompt.rstrip().endswith("PR number:")
+ assert "Respond in English." in prompt
+ assert "git log" not in prompt
+ assert "git diff" not in prompt
+
+
+def test_build_review_prompt_passes_through_args() -> None:
+ prompt = build_review_prompt("123 focus on security")
+ assert prompt.rstrip().endswith("PR number: 123 focus on security")
+ assert "Respond in English." in prompt
+
+
+def test_build_review_prompt_chinese_from_config(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.message_handler.prompts.get_config",
+ lambda: {"preferred_language": "zh"},
+ )
+ prompt = build_review_prompt("42")
+ assert "Respond in Chinese (simplified)." in prompt
+ assert prompt.rstrip().endswith("PR number: 42")
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.py
new file mode 100644
index 0000000000..50009f6c0a
--- /dev/null
+++ b/tests/unit_tests/gateway/test_message_handler_security_review_prompt.py
@@ -0,0 +1,47 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""build_security_review_prompt 单元测试."""
+
+import pytest
+
+from jiuwenswarm.gateway.message_handler.prompts.security_review_prompt import (
+ build_security_review_prompt,
+)
+
+
[email protected](autouse=True)
+def _english_config(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.message_handler.prompts.get_config",
+ lambda: {"preferred_language": "en"},
+ )
+
+
+def test_build_security_review_prompt_runs_git_commands_in_english() -> None:
+ prompt = build_security_review_prompt("")
+ assert "`git status`" in prompt
+ assert "`git diff --name-only origin/HEAD...`" in prompt
+ assert "`git log --no-decorate origin/HEAD...`" in prompt
+ assert "`git diff origin/HEAD...`" in prompt
+ assert "Respond in English." in prompt
+ assert "HIGH-CONFIDENCE security vulnerabilities" in prompt
+ assert "FALSE POSITIVE FILTERING" in prompt
+ assert "Additional instructions:" not in prompt
+ assert "`gh pr" not in prompt
+
+
+def test_build_security_review_prompt_passes_through_args() -> None:
+ prompt = build_security_review_prompt("focus on auth bypass")
+ assert prompt.rstrip().endswith("Additional instructions: focus on auth bypass")
+ assert "Respond in English." in prompt
+
+
+def test_build_security_review_prompt_chinese_from_config(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.message_handler.prompts.get_config",
+ lambda: {"preferred_language": "zh"},
+ )
+ prompt = build_security_review_prompt("")
+ assert "Respond in Chinese (simplified)." in prompt
diff --git a/tests/unit_tests/gateway/test_slash_command.py b/tests/unit_tests/gateway/test_slash_command.py
index 827ef866bf..f118b56f28 100644
--- a/tests/unit_tests/gateway/test_slash_command.py
+++ b/tests/unit_tests/gateway/test_slash_command.py
@@ -71,6 +71,27 @@ parse_channel_control_text = _MOD.parse_channel_control_text
("/rewind confirm 0", ParsedControlAction.REWIND_BAD, None, None, None),
("/rewind confirm abc", ParsedControlAction.REWIND_BAD, None, None, None),
("/rewind cancel", ParsedControlAction.REWIND_CANCEL, None, None, None),
+ ("/review", ParsedControlAction.REVIEW_OK, None, None, None),
+ ("/review 123", ParsedControlAction.REVIEW_OK, None, None, None),
+ (
+ "/review https://github.com/org/repo/pull/123",
+ ParsedControlAction.REVIEW_OK,
+ None,
+ None,
+ None,
+ ),
+ ("/review abc", ParsedControlAction.REVIEW_OK, None, None, None),
+ ("/review 123 focus on security", ParsedControlAction.REVIEW_OK, None, None, None),
+ ("/review bb37e71c33b87199", ParsedControlAction.REVIEW_OK, None, None, None),
+ ("/review bad-arg", ParsedControlAction.REVIEW_OK, None, None, None),
+ ("/security-review", ParsedControlAction.SECURITY_REVIEW_OK, None, None, None),
+ (
+ "/security-review focus on auth",
+ ParsedControlAction.SECURITY_REVIEW_OK,
+ None,
+ None,
+ None,
+ ),
],
)
def test_parse_channel_control_text(
@@ -90,6 +111,38 @@ def test_parse_channel_control_text(
assert p.switch_subcommand is None
assert p.branch_name == branch_name
assert p.rewind_turn == rewind_turn
+ if action is ParsedControlAction.REVIEW_OK:
+ if text == "/review":
+ assert p.pr_arg == ""
+ elif text.startswith("/review "):
+ assert p.pr_arg == text[len("/review "):].strip()
+ elif action is ParsedControlAction.REVIEW_BAD:
+ assert p.pr_arg is None
+ elif action is ParsedControlAction.SECURITY_REVIEW_OK:
+ if text == "/security-review":
+ assert p.security_review_arg == ""
+ elif text.startswith("/security-review "):
+ assert p.security_review_arg == text[len("/security-review "):].strip()
+ elif action is ParsedControlAction.SECURITY_REVIEW_BAD:
+ assert p.security_review_arg is None
+
+
+def test_parse_channel_control_text_review_rejects_unsafe_args() -> None:
+ too_long = "x" * 2049
+ p = parse_channel_control_text(f"/review {too_long}")
+ assert p.action is ParsedControlAction.REVIEW_BAD
+
+ p = parse_channel_control_text("/review bad\x00arg")
+ assert p.action is ParsedControlAction.REVIEW_BAD
+
+
+def test_parse_channel_control_text_security_review_rejects_unsafe_args() -> None:
+ too_long = "x" * 2049
+ p = parse_channel_control_text(f"/security-review {too_long}")
+ assert p.action is ParsedControlAction.SECURITY_REVIEW_BAD
+
+ p = parse_channel_control_text("/security-review bad\x00arg")
+ assert p.action is ParsedControlAction.SECURITY_REVIEW_BAD
def test_control_message_texts_contains_mode_variants_and_skills() -> None:
@@ -122,6 +175,11 @@ def test_is_control_like_for_im_batching() -> None:
assert is_control_like_for_im_batching("/branch fix-login")
assert is_control_like_for_im_batching("/rewind 3")
assert is_control_like_for_im_batching("/rewind")
+ assert is_control_like_for_im_batching("/review")
+ assert is_control_like_for_im_batching("/review 123")
+ assert is_control_like_for_im_batching("/review bad-arg")
+ assert is_control_like_for_im_batching("/security-review")
+ assert is_control_like_for_im_batching("/security-review focus on auth")
assert not is_control_like_for_im_batching("/skills")
assert not is_control_like_for_im_batching("/skills extra")
assert not is_control_like_for_im_batching("")
@@ -146,6 +204,6 @@ def test_first_batch_registry_ids() -> None:
ids = {e.id for e in FIRST_BATCH_REGISTRY}
expected = {
"new_session", "mode", "switch", "skills", "resume",
- "workspace_dir", "branch", "rewind", "recap", "agents",
+ "workspace_dir", "branch", "rewind", "recap", "agents", "review", "security-review",
}
assert ids == expected