Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .codeccignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# CodeCC ignore rules
#
# These files are intentionally excluded from CodeCC secret scanning
# because they are test fixtures containing fake/dummy credentials
# used to validate the ReviewMind secret detection functionality.

# ReviewMind test fixtures with fake secrets (for testing secret detection)
examples/skills_code_review_agent/evals/fixtures/*.diff
examples/skills_code_review_agent/evals/hidden_fixtures/*.diff
examples/skills_code_review_agent/evals/hidden_samples.py
33 changes: 33 additions & 0 deletions examples/skills_code_review_agent/DESIGN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# ReviewMind 方案设计说明

## 项目概述

ReviewMind 是一个基于 tRPC-Agent-Python 框架构建的自动代码评审 Agent,将代码审查流程(diff 解析、规则匹配、静态分析、结果分类、报告生成)封装为可复用、可审计、可评测的系统。核心设计理念是"Skills + 沙箱 + 数据库 + Filter 治理"四层分离,确保每层职责明确、可独立替换。

## Skill 设计

CR Skill (`skills/code-review/`) 采用三层信息模型:SKILL.md 提供技能概览和脚本使用说明,rules/ 目录存放 5 类风险规则文档(安全、异步、资源泄漏、数据库事务、测试缺失),scripts/ 目录存放可在沙箱中执行的检查脚本。Agent 通过 `skill_load` 按需加载规则、通过 `skill_run` 在隔离 workspace 中执行脚本,避免将所有规则文本注入 Prompt 导致 token 浪费。

## 沙箱隔离策略

默认生产方案使用 `ContainerCodeExecutor`(Docker),开发环境 fallback 到 `UnsafeLocalCodeExecutor`。每次执行设 30 秒超时、1MB 输出大小限制,环境变量仅允许白名单内的 `PATH``HOME``PYTHONPATH``WORKSPACE_DIR` 传入。超时或失败的沙箱执行不会导致整个评审任务崩溃,异常信息记录到 `sandbox_run` 表。

## Filter 策略

Filter 链按 `DENY → NEEDS_HUMAN_REVIEW → PASS` 顺序执行,包含 4 类过滤器:`HighRiskScriptFilter`(拦截 rm -rf /、fork 炸弹等危险模式)、`PathSafetyFilter`(禁止访问 /etc、/sys 等敏感路径)、`NetworkAccessFilter`(默认阻断所有网络访问)、`BudgetFilter`(限制执行次数和总时间)。任一 Filter 返回 DENY 时链立即终止,拦截原因写入 `filter_intercept` 表并纳入最终报告。

## 监控字段

每次审查记录以下指标:总耗时、沙箱执行耗时、解析耗时、Filter 耗时、工具调用次数、拦截次数、finding 数量、各 severity 分布、异常类型列表。所有指标持久化到 `monitor_summary` 表,支持按 task_id 查询。

## 数据库 Schema

5 张表:`review_task`(审查任务)、`sandbox_run`(沙箱执行记录)、`finding`(审查发现)、`filter_intercept`(Filter 拦截日志)、`monitor_summary`(监控审计摘要)。使用 SQLite 作为默认实现,`StorageABC` 抽象接口保留了切换 PostgreSQL、MySQL 等后端的空间。Finding 表通过 `dedup_key``file:line:category`)联合索引实现去重。

## 去重降噪

去重规则:同一文件同一行同一类别的 finding 只保留置信度最高的一条。降噪规则:`confidence=low` 的发现自动进入 `needs_human_review` 列表,不混入高置信 findings;`confidence=medium``severity=suggestion` 的发现同样需要人工复核。

## 安全边界

敏感信息脱敏通过 `SecretMasker` 实现,支持 API Key(sk-/pk-)、GitHub Token(ghp_)、AWS Access Key(AKIA)、JWT、数据库连接字符串等 12 种模式的正则匹配和替换。脱敏操作在报告生成阶段执行,确保报告和数据库记录中不出现明文敏感信息。
10 changes: 10 additions & 0 deletions examples/skills_code_review_agent/agent/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Tencent is pleased to support the open source community by making tRPC-Agent-Python available.
#
# Copyright (C) 2026 Tencent. All rights reserved.
#
# tRPC-Agent-Python is licensed under Apache-2.0.
"""Agent module for the code review agent — Phase 3: Learning path enhancement."""

from .agent import create_agent, root_agent

__all__ = ["create_agent", "root_agent"]
72 changes: 72 additions & 0 deletions examples/skills_code_review_agent/agent/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Tencent is pleased to support the open source community by making tRPC-Agent-Python available.
#
# Copyright (C) 2026 Tencent. All rights reserved.
#
# tRPC-Agent-Python is licensed under Apache-2.0.
"""CodeReviewAgent — LlmAgent for the code review pipeline.

Wraps the existing review_agent.run_review() pipeline as a FunctionTool,
enabling interactive multi-turn code review sessions via A2A or AG-UI.
"""

from __future__ import annotations

from trpc_agent_sdk.agents import LlmAgent
from trpc_agent_sdk.models import LLMModel
from trpc_agent_sdk.models import OpenAIModel
from trpc_agent_sdk.tools import load_memory_tool

from .config import get_model_config
from .prompts import INSTRUCTION
from .tools import run_code_review_tool

# Try to load the knowledge search tool; gracefully handle missing deps
_knowledge_tool = None
try:
from ..knowledge import knowledge_search_tool as _kst
_knowledge_tool = _kst
except ImportError:
pass


def _create_model() -> LLMModel:
"""Create a model instance from environment variables."""
api_key, base_url, model_name = get_model_config()
return OpenAIModel(
model_name=model_name,
api_key=api_key,
base_url=base_url,
)


def create_agent() -> LlmAgent:
"""Create the CodeReviewAgent.

The agent wraps the existing review_agent.run_review() pipeline
as a FunctionTool, allowing the LLM to invoke it when the user
provides a diff for review.

Returns:
A configured LlmAgent instance.
"""
return LlmAgent(
name="CodeReviewAgent",
description=(
"A professional code review assistant that analyzes code changes, "
"detects security risks, resource leaks, and other issues, "
"and generates structured review reports."
),
model=_create_model(),
instruction=INSTRUCTION,
tools=[
run_code_review_tool,
load_memory_tool,
_knowledge_tool,
] if _knowledge_tool else [
run_code_review_tool,
load_memory_tool,
],
)


root_agent = create_agent()
26 changes: 26 additions & 0 deletions examples/skills_code_review_agent/agent/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Tencent is pleased to support the open source community by making tRPC-Agent-Python available.
#
# Copyright (C) 2026 Tencent. All rights reserved.
#
# tRPC-Agent-Python is licensed under Apache-2.0.
"""Model configuration for the code review agent.

Reads model settings from environment variables with sensible defaults.
"""

from __future__ import annotations

import os
from typing import Optional


def get_model_config() -> tuple[str, str, str]:
"""Get model configuration from environment variables.

Returns:
Tuple of (api_key, base_url, model_name).
"""
api_key = os.getenv("TRPC_AGENT_API_KEY", "")
base_url = os.getenv("TRPC_AGENT_BASE_URL", "")
model_name = os.getenv("TRPC_AGENT_MODEL_NAME", "deepseek-chat")
return api_key, base_url, model_name
72 changes: 72 additions & 0 deletions examples/skills_code_review_agent/agent/cr_skill.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Tencent is pleased to support the open source community by making tRPC-Agent-Python available.
#
# Copyright (C) 2026 Tencent. All rights reserved.
#
# tRPC-Agent-Python is licensed under Apache-2.0.
"""CR Skill integration for the code review agent.

Wraps the code-review Skill as a SkillToolSet, allowing the Agent to
load rules on demand and run scripts in an isolated sandbox environment.
"""

from __future__ import annotations

import os
from pathlib import Path
from typing import Any, Optional

from trpc_agent_sdk.code_executors import ContainerCodeExecutor, UnsafeLocalCodeExecutor
from trpc_agent_sdk.skills import SkillToolSet


def get_skill_path() -> str:
"""Get the absolute path to the code-review skill directory."""
return str(Path(__file__).resolve().parent.parent / "skills" / "code-review")


def create_skill_toolset(
sandbox_type: str = "local",
timeout: int = 30,
max_output: int = 1_048_576,
) -> SkillToolSet:
"""Create a SkillToolSet for the code-review skill.

Args:
sandbox_type: Sandbox executor type ("local", "container", "cube").
timeout: Max execution time in seconds for each script.
max_output: Max output size in bytes.

Returns:
A configured SkillToolSet instance.
"""
skill_path = get_skill_path()

# Select sandbox executor
if sandbox_type == "container":
code_executor = ContainerCodeExecutor(
timeout=timeout,
max_output_size=max_output,
env_whitelist=["PATH", "HOME", "PYTHONPATH", "WORKSPACE_DIR"],
)
else:
code_executor = UnsafeLocalCodeExecutor(
timeout=timeout,
max_output_size=max_output,
)

return SkillToolSet(
skill_dir=skill_path,
code_executor=code_executor,
)


# Global singleton for easy import
_default_skill_set: Optional[SkillToolSet] = None


def get_skill_toolset() -> SkillToolSet:
"""Get or create the default skill toolset (local sandbox)."""
global _default_skill_set
if _default_skill_set is None:
_default_skill_set = create_skill_toolset()
return _default_skill_set
49 changes: 49 additions & 0 deletions examples/skills_code_review_agent/agent/prompts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Tencent is pleased to support the open source community by making tRPC-Agent-Python available.
#
# Copyright (C) 2026 Tencent. All rights reserved.
#
# tRPC-Agent-Python is licensed under Apache-2.0.
"""Agent instructions for the code review agent.
The instruction is adapted from .github/code_review/prompts/review.md
and tailored for the interactive A2A/AG-UI service mode.
"""

INSTRUCTION = """你是一个资深的代码审查助手,负责审查代码变更并给出高质量的 review 结论。
## 审查范围
1. 只审查用户提供的 diff 或代码变更内容。
2. 可以结合上下文辅助判断,但不要脱离 diff 单独审查未修改代码。
3. 每个问题必须标注文件路径和行号。
## 审查重点
1. 正确性:逻辑错误、状态流转错误、条件判断错误、返回值或异常处理错误。
2. 安全性:凭证泄露、命令注入、路径穿越、不可信输入未校验、权限绕过。
3. 稳定性:边界条件缺失、空值处理、并发或异步时序问题、资源未释放。
4. 兼容性:公开 API、配置项、持久化数据的破坏性变更。
5. 测试有效性:高风险逻辑缺少必要测试。
6. 可维护性:仅在影响理解或长期维护时提出。
## 质量等级
- 🚨 Critical:必须修复的问题。安全漏洞、明确的逻辑错误、核心功能失败。
- ⚠️ Warning:建议修复的问题。性能隐患、边界条件缺失、异常路径不完整。
- 💡 Suggestion:可选优化。代码可读性、结构简化、维护性提升。
## 工具使用
你有一个 `run_code_review` 工具,它接受 diff 内容并运行自动化的代码审查流程,
包括 diff 解析、沙箱执行、静态检查、敏感信息检测等。
当用户提交代码变更时,调用此工具进行审查。
审查完成后,根据工具返回的结果,向用户解释发现的问题。
## 工作流程
1. 当用户提供 diff 或代码变更时,调用 `run_code_review` 工具进行全面审查
2. 审查完成后,向用户摘要说明 findings 的数量和严重级别分布
3. 用户可以针对某个 finding 追问细节,你需要根据工具返回的结果进行解释
4. 如果用户询问修复建议,根据 recommendation 字段给出具体建议
## 输出要求
- 先列问题,再给总结
- 按 Critical、Warning、Suggestion 的顺序输出
- 每条问题说明问题、影响和修复方向
- 结论要尽量确定,不要使用"可能""疑似"等模糊措辞
"""
Loading
Loading