关于 arch-security-review
arch-security-review 是用于代码审查的仓库技能,依据 OWASP Top 10 和项目安全规范检查代码。它指导检查前后端攻击面,并以严重级别和代码示例记录问题。
主要功能
- 01OWASP Top 10 审计清单
- 02检查前后端安全风险
- 03核验授权与输入验证
- 04检查敏感数据和依赖项
- 05按严重级别附代码示例报告
适用场景
- 01审计涉及安全的代码变更
- 02检查身份验证与授权
- 03评估数据保护和漏洞
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ duc01226/ easyplatform --skill arch-security-review安装后在 Claude Code 中输入/arch-security-review确认已加载。
详细介绍
Codex 兼容性说明:
- 在 Codex 中使用
$skill-name调用仓库技能;此镜像副本会将旧版 Claude/skill-name引用改写为$skill-name。- 任务跟踪要求:执行任何工作流或技能步骤之前,必须为所有步骤创建或更新任务跟踪,并随着进度变化保持同步。
- 面向用户的问题提示表示应直接在 Codex 中询问用户。
- 遇到 Claude 专属的模式切换指令时,请忽略。
- 严格执行约定:用户明确调用某项技能时,必须按原样执行该技能协议。
- 子 Agent 授权:当技能由用户调用或 AI 检测到,且其协议要求使用子 Agent 时,该技能激活即授权为该任务使用所需的
spawn_agent子 Agent。- 除非用户事先明确批准偏离,否则不得跳过、重排或合并协议步骤。
- 对于工作流技能,必须明确执行每个列出的子技能步骤,并逐步报告证据。
- 如果所需步骤或工具在此环境中无法运行,请停止并在调整方案前询问用户。
Codex 项目参考资料加载(无钩子)
Codex 不会收到基于 Claude 钩子的文档注入。 进行编码、规划、调试、测试或审查时,请按以下路径显式打开项目文档。
始终阅读:
docs/project-config.json(项目专属路径、命令、模块和工作流/测试设置)docs/project-reference/docs-index-reference.md(指向完整docs/project-reference/*目录的索引)docs/project-reference/lessons.md(始终适用的防护措施和反模式)
按情况阅读的文档:
- 后端/CQRS/API/领域/实体变更:
backend-patterns-reference.md、domain-entities-reference.md、project-structure-reference.md - 前端/UI/样式/设计系统:
frontend-patterns-reference.md、scss-styling-guide.md、design-system/README.md - 规范/测试用例规划或 TC 映射:
feature-docs-reference.md - 集成测试实现/审查:
integration-test-reference.md - E2E 测试实现/审查:
e2e-test-reference.md - 代码审查/审计工作:
code-review-rules.md,以及根据变更文件选择的领域文档
不要不加区分地阅读所有文档。从 docs-index-reference.md 开始,然后只打开与任务相关的文件。
快速摘要
**目标:**依据 OWASP Top 10 审查代码中的安全漏洞,并落实授权、数据保护和安全编码模式。
工作流:
- 预检 — 识别安全敏感区域,检查 OWASP 相关性,审查现有模式
- OWASP 审计 — 按全部 10 个类别评估代码(访问控制、注入、身份验证等)
- 项目检查 — 验证授权属性、实体访问表达式和输入验证
- 报告 — 通过严重性、安全与易受攻击的代码示例记录发现
关键规则:
- 始终检查后端和前端攻击面
- 使用项目授权属性和实体级访问表达式,绝不依赖仅 UI 端的防护(参见 docs/project-reference/backend-patterns-reference.md)
- 使用项目验证 API 验证所有外部数据,绝不信任客户端输入(参见 docs/project-reference/backend-patterns-reference.md)
保持审慎。运用批判性思维和顺序思维。每项结论都必须有可追溯的证据和置信度百分比(Idea 应高于 80%)。
安全审查工作流
何时使用此技能
- 代码变更的安全审计
- 实现身份验证/授权
- 数据保护审查
- 漏洞评估
预检清单
- 识别安全敏感区域
- 审查 OWASP Top 10 的相关性
- 检查现有安全模式
- 规划修复方案
OWASP Top 10 清单
1. 访问控制失效
// :x: VULNERABLE - No authorization check
[HttpGet("{id}")]
public async Task<Employee> Get(string id)
=> await repo.GetByIdAsync(id);
// :white_check_mark: SECURE - Authorization enforced
[HttpGet("{id}")]
[Authorize(Roles.Manager, Roles.Admin)] // project authorization attribute (see docs/project-reference/backend-patterns-reference.md)
public async Task<Employee> Get(string id)
{
var employee = await repo.GetByIdAsync(id);
// Verify access to this specific resource
if (employee.CompanyId != RequestContext.CurrentCompanyId())
throw new UnauthorizedAccessException();
return employee;
}
2. 加密失败
// :x: VULNERABLE - Storing plain text secrets
var apiKey = config["ApiKey"];
await SaveToDatabase(apiKey);
// :white_check_mark: SECURE - Encrypt sensitive data
var encryptedKey = encryptionService.Encrypt(apiKey);
await SaveToDatabase(encryptedKey);
// Use secure configuration
var apiKey = config.GetValue<string>("ApiKey"); // From Azure Key Vault
3. 注入
// :x: VULNERABLE - SQL Injection
var sql = $"SELECT * FROM Users WHERE Name = '{name}'";
await context.Database.ExecuteSqlRawAsync(sql);
// :white_check_mark: SECURE - Parameterized query
await context.Users.Where(u => u.Name == name).ToListAsync();
// Or if raw SQL needed:
await context.Database.ExecuteSqlRawAsync(
"SELECT * FROM Users WHERE Name = @p0", name);
4. 不安全设计
// :x: VULNERABLE - No rate limiting
[HttpPost("login")]
public async Task<IActionResult> Login(LoginRequest request)
=> await authService.Login(request);
// :white_check_mark: SECURE - Rate limiting applied
[HttpPost("login")]
[RateLimit(MaxRequests = 5, WindowSeconds = 60)]
public async Task<IActionResult> Login(LoginRequest request)
=> await authService.Login(request);
5. 安全配置错误
// :x: VULNERABLE - Detailed errors in production
app.UseDeveloperExceptionPage(); // Exposes stack traces
// :white_check_mark: SECURE - Generic errors in production
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Error");
6. 易受攻击的组件
# Check for vulnerable packages
dotnet list package --vulnerable
# Update vulnerable packages
dotnet outdated
7. 身份验证失败
// :x: VULNERABLE - Weak password policy
if (password.Length >= 4) { }
// :white_check_mark: SECURE - Strong password policy
public class PasswordPolicy
{
public bool Validate(string password)
{
return password.Length >= 12
&& password.Any(char.IsUpper)
&& password.Any(char.IsLower)
&& password.Any(char.IsDigit)
&& password.Any(c => !char.IsLetterOrDigit(c));
}
}
8. 数据完整性失败
// :x: VULNERABLE - No validation of external data
var userData = await externalApi.GetUserAsync(id);
await SaveToDatabase(userData);
// :white_check_mark: SECURE - Validate external data
var userData = await externalApi.GetUserAsync(id);
var validation = userData.Validate();
if (!validation.IsValid)
throw new ValidationException(validation.Errors);
await SaveToDatabase(userData);
9. 日志记录失败
// :x: VULNERABLE - Logging sensitive data
Logger.LogInformation("User login: {Email} {Password}", email, password);
// :white_check_mark: SECURE - Redact sensitive data
Logger.LogInformation("User login: {Email}", email);
// Never log passwords, tokens, or PII
10. SSRF(服务器端请求伪造)
// :x: VULNERABLE - User-controlled URL
var url = request.WebhookUrl;
await httpClient.GetAsync(url); // Could access internal services
// :white_check_mark: SECURE - Validate and restrict URLs
if (!IsAllowedUrl(request.WebhookUrl))
throw new SecurityException("Invalid webhook URL");
private bool IsAllowedUrl(string url)
{
var uri = new Uri(url);
return AllowedDomains.Contains(uri.Host)
&& uri.Scheme == "https";
}
授权模式
⚠️ 务必阅读: CLAUDE.md,了解授权控制器/处理程序模式、RequestContext 的用法以及实体级访问筛选器(参见 docs/project-reference/backend-patterns-reference.md)。
数据保护
敏感数据处理
public class SensitiveDataHandler
{
// Encrypt at rest
public string EncryptForStorage(string plainText)
=> encryptionService.Encrypt(plainText);
// Mask for display
public string MaskEmail(string email)
{
var parts = email.Split('@');
return $"{parts[0][0]}***@{parts[1]}";
}
// Never log sensitive data
public void LogUserAction(User user)
{
Logger.LogInformation("User action: {UserId}", user.Id);
// NOT: Logger.Log("User: {Email} {Phone}", user.Email, user.Phone);
}
}
文件上传安全
public async Task<IActionResult> Upload(IFormFile file)
{
// Validate file type
var allowedTypes = new[] { ".pdf", ".docx", ".xlsx" };
var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
if (!allowedTypes.Contains(extension))
return BadRequest("Invalid file type");
// Validate file size
if (file.Length > 10 * 1024 * 1024) // 10MB
return BadRequest("File too large");
// Scan for malware (if available)
if (!await antivirusService.ScanAsync(file))
return BadRequest("File rejected by security scan");
// Generate safe filename
var safeFileName = $"{Guid.NewGuid()}{extension}";
// Save to isolated storage
await fileService.SaveAsync(file, safeFileName);
return Ok();
}
安全扫描命令
# .NET vulnerability scan
dotnet list package --vulnerable
# Outdated packages
dotnet outdated
# Secret scanning
grep -r "password\|secret\|apikey" --include="*.cs" --include="*.json"
# Hardcoded credentials
grep -r "Password=\"" --include="*.cs"
grep -r "connectionString.*password" --include="*.json"
安全审查清单
身份验证
- 强密码策略已启用
- 多次尝试失败后锁定账户
- 会话管理安全
- JWT 令牌已正确验证
- 刷新令牌已轮换
授权
- 所有端点都要求身份验证
- 已实现基于角色的访问控制
- 已检查资源级权限
- 无法提升权限
输入验证
- 已验证所有输入
- 已防止 SQL 注入(使用参数化查询)
- 已防止 XSS(对输出进行编码)
- 已验证文件上传
- 已验证重定向 URL
数据保护
- 静态敏感数据已加密
- 已强制使用 HTTPS
- 日志中不含敏感数据
- 错误处理得当(不包含堆栈跟踪)
依赖项
- 不含已知存在漏洞的软件包
- 定期更新依赖项
- 已审查第三方代码
应避免的反模式
:x: 信任客户端输入
var isAdmin = request.IsAdmin; // User-supplied!
:x: 暴露内部错误
catch (Exception ex) { return BadRequest(ex.ToString()); }
:x: 硬编码机密
var apiKey = "sk_live_xxxxx";
:x: 日志记录不足
// No audit trail for sensitive operations
await DeleteAllUsers();
验证清单
- 已审查 OWASP Top 10
- 已验证身份验证/授权
- 已完成输入验证
- 已保护敏感数据
- 不含硬编码机密
- 日志记录恰当(不含个人身份信息)
- 已扫描依赖项
相关内容
arch-performance-optimizationarch-cross-service-integrationcode-review
[IMPORTANT] 开始前,使用任务跟踪将所有工作拆分为小任务——包括为每个要读取的文件创建任务。这样可以避免因文件过长而丢失上下文。对于简单任务,AI 务必先询问用户是否跳过。
docs/project-reference/domain-entities-reference.md— 领域实体目录、关系、跨服务同步(任务涉及业务实体/模型时阅读)(相关时直接阅读;不要依赖钩子注入的对话文本)
核心目的: 确保质量——不留缺陷、无错误、不遗漏更新、不留过时内容。验证代码和文档。 AI 错误预防 — 每项任务都要避免的失败模式:
删除前检查下游引用。 删除组件会导致文档和代码连锁过时。移除前,先梳理所有引用文件。 根据实际代码核实 AI 生成的内容。 AI 会幻觉出 API、类名和方法签名。记录或引用前,务必通过 grep 确认其存在。 编辑后追踪完整依赖链。 修改定义时,容易遗漏由此派生的下游变量和使用者。务必追踪完整链路。 验证正确性时追踪所有代码路径。 确认代码存在,不代表它会执行。务必追踪提前退出、错误分支和条件跳过,而不只是正常路径。 调试时,先问“由谁负责?”,再修复。 追查问题出在调用方(数据错误)还是被调用方(处理错误)。在责任所在的层修复,切勿只修补症状出现的位置。 假定现有值是有意设定的——修改前先问“为什么”。 更改任何常量、限制、标志或模式前:阅读注释、检查 git blame、查看周边代码。 核实所有受影响的输出,而不只是第一个。 涉及多个技术栈的更改,需要核实每一项输出。一个检查通过,不代表所有检查都通过。 先全局排查——避免注意力就近偏误。 调查任何故障时,先列出所有前置条件(配置、环境变量、数据库名称、端点、DI 注册、数据前提),再逐一根据证据核实,之后才能提出任何代码层面的假设。 精准修改——执行差异测试。 修复错误:每一处更改都必须能直接追溯到该错误。不要顺手调整格式或改进相邻代码。增强任务:实现改进并明确说明。 编码前明确歧义——不要默默自行选择。 如果请求有多种解释,请逐一列出并估算工作量,然后询问。切勿默认选择处理所有记录、基于文件或更复杂的路径。
嵌套任务展开约定 — 对工作流步骤的调用而言,
[Workflow] ...行只是父容器;子技能仍需创建可见的阶段任务。
- 首先调用当前任务列表。如果存在匹配的活动父工作流行,则设置
nested=true并记录parentTaskId;否则独立运行。- 阶段工作开始前,为每个声明的阶段创建一个任务。嵌套时,任务主题前缀为
[N.M] $skill-name — phase。- 嵌套时,通过
TaskUpdate(parentTaskId, addBlockedBy: [childIds])关联父任务。- 编排器必须在调用子技能或子 Agent 前,预先展开其阶段列表,并关联工作流行。
- 开始工作前,恰好将一个子任务标记为
in_progress;写入证据后立即将其标记为completed。- 只有在所有子任务都已完成,或已明确说明原因并取消后,才能完成父任务。
解除阻塞条件: 当前任务列表已完成、子阶段已创建、嵌套时已关联父任务、第一个子任务已标记为
in_progress。 项目参考文档门槛 — 在完成任务跟踪初始化后、读取目标文件或源文件、执行 grep、编辑或分析之前运行。项目文档优先于通用框架假设。
- 确定范围:文件类型、领域和操作。
- 根据触发条件确定必需文档:始终阅读
docs/project-reference/lessons.md;查询文档时阅读docs-index-reference.md;审查时阅读code-review-rules.md;后端/CQRS/API 时阅读backend-patterns-reference.md;领域/实体时阅读domain-entities-reference.md;前端/UI 时阅读frontend-patterns-reference.md;样式/设计时阅读scss-styling-guide.md+design-system/design-system-canonical.md;集成测试时阅读integration-test-reference.md;E2E 时阅读e2e-test-reference.md;功能文档/规格时阅读feature-docs-reference.md;架构/新领域时阅读project-structure-reference.md。- 阅读所有存在的必需文档;缺失的文档视为不适用并跳过。不要将对话中的文字(例如
[Injected: <path>])当作当前上下文已包含该文档的证明。- 开始目标工作前,说明:
Reference docs read: ... | Missing/not applicable: ...。解除阻塞条件: 已评估范围、已检查/阅读必需文档、已确认
lessons.md,并已给出引用。
任务跟踪与外部报告持久化 — 执行前先完成此初始化;随后在处理目标内容前预读取项目参考文档。
- 在读取目标文件或源文件、执行 grep、编辑或分析之前,创建简短的任务拆解。上下文丢失时,先检查当前任务列表。
- 开始工作前将一个任务标记为
in_progress;取得证据后立即标记为completed;绝不批量转换状态。- 对计划/审查工作,在发现第一个问题前创建
plans/reports/{skill}-{YYMMDD}-{HHmm}-{slug}.md。- 每完成一个文件、章节或决策后追加发现,并在最后根据报告文件进行综合。
- 最终输出引用:
Full report: plans/reports/{filename}。解除阻塞条件: 已创建任务拆解;计划/审查工作已声明报告路径;在记录下一个发现前,已持久化第一个发现。
批判性思维模式 — 运用批判性思维和顺序思维。每项断言都需要可追溯的证据,置信度 >80% 才能采取行动。 防止幻觉: 绝不将猜测说成事实——为每项断言引用来源,坦诚承认不确定性,自查输出错误,独立交叉验证,始终对自己的判断保持怀疑——没有证据却确信无疑,是所有幻觉的根源。
基于证据的推理 — 禁止推测。每项断言都需要证据。
- 为每项断言引用
file:line、grep 结果或框架文档- 声明置信度:>80% 可直接行动,60-80% 先验证,<60% 不要推荐
- 架构变更必须进行跨服务验证
- “证据不足”是有效且预期的输出
解除阻塞条件:
- [ ]证据文件路径(file:line)- [ ]已执行 grep 搜索- [ ]已找到 3 个或以上类似模式- [ ]已说明置信度禁止在没有证据时使用: “显而易见”“我认为”“应该”“可能”“这是因为” 如果未完成 → 输出:
"证据不足。已验证:[...]。未验证:[...]。"由修复触发的重新审查循环 — 重新审查由修复周期触发,而非由轮次编号触发。审查流程:review → if issues → fix → re-review,直至某一轮未发现问题。审查通过后循环即结束——无需进行后续轮次。第 1 轮: 主会话审查。阅读目标文件,建立理解,记录问题。输出发现结果和结论(PASS / FAIL)。
第 1 轮后的决策:
- 未发现问题(PASS,发现数为零) → 审查结束。不要启动新的子 Agent 进行确认。
- 发现问题(FAIL,或发现数不为零) → 修复问题,然后启动新的子 Agent 进行第 2 轮重新审查。
由新的子 Agent 重新审查(每次修复周期之后): 启动一次新的
spawn_agent工具调用——绝不重复使用之前的 Agent。子 Agent 从头重新阅读所有文件,不保留此前各轮的任何记忆。启动机制请参见SYNC:fresh-context-review,标准 Agent 提示词模板请参见SYNC:review-protocol-injection。每一轮新的审查都必须发现:
- 前一轮遗漏的跨领域问题
- 已更改文件之间的交互问题
- 规范偏差(新代码与现有模式不一致)
- 应当存在但缺失的部分
- 前一轮以理由搪塞过去的细微边界情况
- 修复本身引入的回归问题
循环终止: 每轮新的审查结束后,重复相同决策:无问题 → 结束;有问题 → 修复 → 进入下一轮新的审查。持续执行,直到某一轮发现数为零,或达到最多 3 轮新的子 Agent 审查,然后通过直接向用户提问来升级处理。
规则:
- 第 1 轮审查通过即结束——无需强制进行第 2 轮
- 修复周期后绝不跳过新的子 Agent 重新审查(每次修复都会使之前的结论失效)
- 各轮之间绝不重复使用子 Agent——每次迭代都要启动一次新的 Agent 调用
- 主 Agent 必须阅读子 Agent 报告,但不得筛选、重新解读或否定其中的发现
- 每次审查最多进行 3 轮新的子 Agent 审查——如果仍为 FAIL,则通过直接向用户提问来升级处理(不得默默继续循环)
- 在对话上下文中跟踪轮次计数(仅限当前会话)
- 最终结论必须纳入所有已执行轮次的结果
报告必须包含每个已执行的第 N 轮(N≥2)的
## Round N Findings (Fresh Sub-Agent)。 全新子 Agent 审查 — 通过隔离的子 Agent 消除协调者的确认偏误。原因: 主 Agent 知道自己(或
$cook)刚修复了什么,并会据此合理化审查结果。全新的子 Agent 完全没有记忆,会从头重新阅读,并发现主 Agent 忽略的问题。通过以下方式缓解子 Agent 偏误:(1)使用全新上下文,(2)逐字注入协议,(3)主 Agent 不筛选报告。何时: 仅在修复周期之后进行。若某轮审查未发现问题,则结束循环——不要启动确认性子 Agent。若某轮审查发现问题,则执行:修复 → 全新子 Agent 重新审查。
方法:
- 启动一次新的
spawn_agent工具调用——代码审查使用code-revieweragent_type,计划/文档/制品审查使用general-purpose- 将所有必需的审查协议逐字注入提示词——完整列表和模板见
SYNC:review-protocol-injection。切勿通过文件路径引用协议;经由文件读取间接传递会降低 AI 的遵循度(见SYNC:shared-protocol-duplication-policy)- 子 Agent 通过自己的工具调用从头重新读取所有目标文件——切勿在提示词中直接传入文件内容
- 子 Agent 将结构化报告写入
plans/reports/{review-type}-round{N}-{date}.md- 主 Agent 阅读报告,将审查结果整合进自己的报告,不得覆盖或筛选
规则:
- 若上一轮未发现问题,则跳过全新子 Agent(没有修复,就没有新内容需要验证)
- 修复周期之后绝不能跳过全新子 Agent——每次修复都会使先前的结论失效
- 绝不能在多轮审查中重复使用同一个子 Agent——每一轮全新的审查都必须启动一次新的
spawn_agent调用- 每次审查最多进行 3 轮全新子 Agent 审查——若仍未通过,则通过直接向用户提问来升级处理;不要默默循环,也不要回退到任何先前的协议
- 在对话上下文中跟踪迭代次数(仅限会话,不使用持久化文件)
审查协议注入 — 每个全新子 Agent 审查提示词都必须逐字包含 10 个协议块。下方模板已将全部 10 个协议正文展开内嵌。运行时将整个模板原样复制到 Agent 调用的
prompt字段中,仅替换 Task / Round / Reference Docs / Target Files / Output 部分的{placeholders},填入与上下文相符的值。不要改动内嵌的协议部分。为何内联展开: 占位符标记会导致运行时通过文件读取间接传递。经由间接传递会显著降低 AI 的遵循度(见
SYNC:shared-protocol-duplication-policy)。因此,模板预先内嵌了全部 10 个协议正文。
子 Agent 类型选择
code-reviewer— 用于代码审查(审查源文件、git 差异、实现)general-purpose— 用于计划/文档/制品审查(审查 Markdown 计划、文档、规格说明)
标准 Agent 调用模板(逐字复制)
spawn_agent({
description: "Fresh Round {N} review",
agent_type: "code-reviewer",
prompt: `
## Task
{review-specific task — e.g., "Review all uncommitted changes for code quality" | "Review plan files under {plan-dir}" | "Review integration tests in {path}"}
## Round
Round {N}. You have ZERO memory of prior rounds. Re-read all target files from scratch via your own tool calls. Do NOT trust anything from the main agent beyond this prompt.
## Protocols (follow VERBATIM — these are non-negotiable)
### Evidence-Based Reasoning
Speculation is FORBIDDEN. Every claim needs proof.
1. Cite file:line, grep results, or framework docs for EVERY claim
2. Declare confidence: >80% act freely, 60-80% verify first, <60% DO NOT recommend
3. Cross-service validation required for architectural changes
4. "I don't have enough evidence" is valid and expected output
BLOCKED until: Evidence file path (file:line) provided; Grep search performed; 3+ similar patterns found; Confidence level stated.
Forbidden without proof: "obviously", "I think", "should be", "probably", "this is because".
If incomplete → output: "Insufficient evidence. Verified: [...]. Not verified: [...]."
### Bug Detection
MUST check categories 1-4 for EVERY review. Never skip.
1. Null Safety: Can params/returns be null? Are they guarded? Optional chaining gaps? .find() returns checked?
2. Boundary Conditions: Off-by-one (< vs <=)? Empty collections handled? Zero/negative values? Max limits?
3. Error Handling: Try-catch scope correct? Silent swallowed exceptions? Error types specific? Cleanup in finally?
4. Resource Management: Connections/streams closed? Subscriptions unsubscribed on destroy? Timers cleared? Memory bounded?
5. Concurrency (if async): Missing await? Race conditions on shared state? Stale closures? Retry storms?
6. Stack-Specific: JS: === vs ==, typeof null. C#: async void, missing using, LINQ deferred execution.
Classify: CRITICAL (crash/corrupt) → FAIL | HIGH (incorrect behavior) → FAIL | MEDIUM (edge case) → WARN | LOW (defensive) → INFO.
### Design Patterns Quality
Priority checks for every code change:
1. DRY via OOP: Same-suffix classes (*Entity, *Dto, *Service) MUST share base class. 3+ similar patterns → extract to shared abstraction.
2. Right Responsibility: Logic in LOWEST layer (Entity > Domain Service > Application Service > Controller). Never business logic in controllers.
3. SOLID: Single responsibility (one reason to change). Open-closed (extend, don't modify). Liskov (subtypes substitutable). Interface segregation (small interfaces). Dependency inversion (depend on abstractions).
4. After extraction/move/rename: Grep ENTIRE scope for dangling references. Zero tolerance.
5. YAGNI gate: NEVER recommend patterns unless 3+ occurrences exist. Don't extract for hypothetical future use.
Anti-patterns to flag: God Object, Copy-Paste inheritance, Circular Dependency, Leaky Abstraction.
### Logic & Intention Review
Verify WHAT code does matches WHY it was changed.
1. Change Intention Check: Every changed file MUST serve the stated purpose. Flag unrelated changes as scope creep.
2. Happy Path Trace: Walk through one complete success scenario through changed code.
3. Error Path Trace: Walk through one failure/edge case scenario through changed code.
4. Acceptance Mapping: If plan context available, map every acceptance criterion to a code change.
5. Tests Verify Intent: For test/spec changes, verify tests name the protected business rule or invariant and would fail if that intent breaks.
6. Migration Test Exclusion: Do not write tests for migration code. Schema/data migrations are one-time execution paths, not core application logic.
NEVER mark review PASS without completing both traces (happy + error path).
### Test Spec Verification
Map changed code to test specifications.
1. Identify the project's test/spec format from existing docs, test-case files, BDD feature files, or spec folders.
2. Every changed code path MUST map to a corresponding test case/spec (or flag as "needs test case").
3. New functions/endpoints/handlers → flag for test spec creation.
4. Migration files are excluded from test/spec creation; schema/data migrations are one-time execution paths, not core application logic.
5. If spec evidence fields exist, verify they point to actual code (file:line, not stale references).
6. Verify each meaningful test case names the business intent/invariant; flag behavior-only cases that only mirror implementation details.
7. Auth/data changes → verify corresponding authorization and data-state test cases exist.
8. If no specs exist for a changed path → log the gap and recommend the project's test-spec workflow.
NEVER skip test mapping. Untested code paths are the #1 source of production bugs.
### Behavioral Delta Matrix
MANDATORY for any bugfix review. Produce input-state × pre-fix × post-fix × delta table BEFORE writing verdict.
- Minimum 3 rows; include at least one row OUTSIDE the original bug report.
- Any "REGRESSION" delta → review returns FAIL until a preservation test is added.
- Narrative descriptions do NOT substitute for the matrix.
Example rows (external-record sync fix):
| Input | Pre-fix | Post-fix | Delta |
| --------------------- | ------- | ------------------------- | ---------- |
| Record exists (valid) | Reused | Always recreated → orphan | REGRESSION |
| Record missing (404) | Error | Recreated | Fixed |
### Fix-Layer Accountability
NEVER fix at the crash site. Trace the full flow, fix at the owning layer. The crash site is a SYMPTOM, not the cause.
MANDATORY before ANY fix:
1. Trace full data flow — Map the complete path from data origin to crash site across ALL layers (storage → backend → API → frontend → UI). Identify where bad state ENTERS, not where it CRASHES.
2. Identify the invariant owner — Which layer's contract guarantees this value is valid? Fix at the LOWEST layer that owns the invariant, not the highest layer that consumes it.
3. One fix, maximum protection — If fix requires touching 3+ files with defensive checks, you are at the wrong layer — go lower.
4. Verify no bypass paths — Confirm all data flows through the fix point. Check for direct construction skipping factories, clone/spread without re-validation, raw data not wrapped in domain models, mutations outside the model layer.
BLOCKED until: Full data flow traced (origin → crash); Invariant owner identified with file:line evidence; All access sites audited (grep count); Fix layer justified (lowest layer that protects most consumers).
Anti-patterns (REJECT): "Fix it where it crashes" (crash site ≠ cause site, trace upstream); "Add defensive checks at every consumer" (scattered defense = wrong layer); "Both fix is safer" (pick ONE authoritative layer).
### Rationalization Prevention
AI skips steps via these evasions. Recognize and reject:
- "Too simple for a plan" → Simple + wrong assumptions = wasted time. Plan anyway.
- "I'll test after" → RED before GREEN. Write/verify test first.
- "Already searched" → Show grep evidence with file:line. No proof = no search.
- "Just do it" → Still need task tracking. Skip depth, never skip tracking.
- "Just a small fix" → Small fix in wrong location cascades. Verify file:line first.
- "Code is self-explanatory" → Future readers need evidence trail. Document anyway.
- "Combine steps to save time" → Combined steps dilute focus. Each step has distinct purpose.
### Graph-Assisted Investigation
MANDATORY when .code-graph/graph.db exists.
HARD-GATE: MUST run at least ONE graph command on key files before concluding any investigation.
Pattern: Grep finds files → trace --direction both reveals full system flow → Grep verifies details.
- Investigation/Scout: trace --direction both on 2-3 entry files
- Fix/Debug: callers_of on buggy function + tests_for
- Feature/Enhancement: connections on files to be modified
- Code Review: tests_for on changed functions
- Blast Radius: trace --direction downstream
CLI: python .claude/scripts/code_graph {command} --json. Use --node-mode file first (10-30x less noise), then --node-mode function for detail.
### Understand Code First
HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
1. Search 3+ similar patterns (grep/glob) — cite file:line evidence.
2. Read existing files in target area — understand structure, base classes, conventions.
3. Run python .claude/scripts/code_graph trace <file> --direction both --json when .code-graph/graph.db exists.
4. Map dependencies via connections or callers_of — know what depends on your target.
5. Write investigation to .ai/workspace/analysis/ for non-trivial tasks (3+ files).
6. Re-read analysis file before implementing — never work from memory alone.
7. NEVER invent new patterns when existing ones work — match exactly or document deviation.
BLOCKED until: Read target files; Grep 3+ patterns; Graph trace (if graph.db exists); Assumptions verified with evidence.
## Reference Docs (READ before reviewing)
- docs/project-reference/code-review-rules.md
- {skill-specific reference docs — e.g., integration-test-reference.md for integration-test-review; backend-patterns-reference.md for backend reviews; frontend-patterns-reference.md for frontend reviews}
## Target Files
{explicit file list OR "run git diff to see uncommitted changes" OR "read all files under {plan-dir}"}
## Output
Write a structured report to plans/reports/{review-type}-round{N}-{date}.md with sections:
- Status: PASS | FAIL
- Issue Count: {number}
- Critical Issues (with file:line evidence)
- High Priority Issues (with file:line evidence)
- Medium / Low Issues
- Cross-cutting findings
Return the report path and status to the main agent.
Every finding MUST have file:line evidence. Speculation is forbidden.
`
})
规则
-
必须完整复制模板,包括所有 10 个内嵌的协议章节
-
只替换 Task / Round / Reference Docs / Target Files / Output 部分中的
{placeholders},并填入与上下文相关的内容 -
代码审查选择
code-revieweragent_type;计划 / 文档 / 成果审查选择general-purpose -
不得改写、总结或跳过任何协议章节
-
不得以内联方式传递文件内容——子 Agent 会通过自己的工具调用读取文件,因此拥有全新的上下文
-
不得通过文件路径或标签名称引用协议——协议正文已在上方内嵌
-
不得为协议引入占位符标记——协议必须保持完整展开
-
强制:重要,务必注意 每项主张都必须引用
file:line证据。只有置信度 >80% 才能采取行动;置信度 <60% 时,不得提出建议。
务必注意 运用批判性思维——每项主张都必须有可追溯的证据,只有置信度 >80% 才能采取行动。防幻觉:绝不把猜测当作事实来陈述。
务必注意 运用 AI 错误预防措施——优先从整体着手调试,在责任层修复问题,编码前明确指出歧义,压缩上下文后重新阅读文件。
-
强制 在处理目标之前初始化任务跟踪;一次只推进一个任务。
-
强制 将计划 / 审查结果逐步保存到
plans/reports/,并从磁盘上的内容综合整理。 -
强制 在初始化任务跟踪之后、处理目标 / 源文件之前,阅读必需的项目参考文档,并引用
Reference docs read: ...。 -
强制 始终包含
lessons.md;项目约定优先于通用默认设置。 -
强制 父工作流中的任务行不能替代子阶段跟踪;嵌套时应展开各阶段并链接到父任务。
-
强制 编排者须在调用前预先展开子技能阶段;使用
[N.M] $skill-name — phase前缀,并遵守同一时间仅一个任务处于in_progress的原则。
收尾提醒
- 强制:重要,务必注意 使用任务跟踪将工作拆分为小型待办任务,并在开始前完成
- 强制:重要,务必注意 新增代码前,在代码库中搜索至少 3 个相似模式
- 强制:重要,务必注意 每项主张都必须引用
file:line证据(只有置信度 >80% 才能采取行动) - 强制:重要,务必注意 添加最终审查待办任务,以验证工作质量
- 强制:重要,务必注意 按照
SYNC:double-round-trip-review执行多轮审查:第 1 轮在主会话中进行,第 2 轮及之后的审查通过按SYNC:fresh-context-review+SYNC:review-protocol-injection启动的全新code-reviewer子 Agent 完成 强制:重要,务必注意 开始前,阅读以下文件:
[TASK-PLANNING] 行动前,分析任务范围,并使用任务跟踪系统将其系统性地拆分为小型待办任务和子任务。
无 Hook 提示词协议镜像(自动同步)
来源:.claude/hooks/lib/prompt-injections.cjs + .claude/.ck.json
[WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] 工作流执行协议 — 强制、重要、必须、关键。无论出于何种原因,都不得跳过。
通用可移植性边界: 可复用的技能和协议文本应与项目无关;从 docs/project-config.json 和 docs/project-reference/ 中查找项目特定约定。应用 shared/sdd-artifact-contract.md 中的共享 AI-SDD。阅读 docs/project-config.json 和 docs/project-reference/docs-index-reference.md,然后打开其中列出的项目参考文档。只要具备此共享上下文和本地文档,任何受支持的 AI 工具都可以执行。
- 检测: 将提示词与工作流目录进行匹配
- 分析: 找出最匹配的工作流,并评估自定义步骤组合是否更合适
- 询问(必需格式): 直接向用户提问,采用以下结构;除非用户明确调用了某个工作流/技能,且本地协议将明确调用视为确认:
- 问题:"你想启用哪个工作流?"
- 选项 1:"启用 [最佳匹配工作流](推荐)"
- 选项 2:"启用自定义工作流:[步骤 1 → 步骤 2 → ...]"(附上一句话说明理由)
- 启用(确认后): 标准工作流调用
$workflow-start <workflowId>;自定义步骤按顺序手动执行 - 创建任务: 跟踪工作流的所有步骤
- 执行: 按顺序遵循每个步骤 [CRITICAL-THINKING-MINDSET] 运用批判性思维和顺序思维。每项声明都必须有可追溯的证据;置信度超过 80% 才能采取行动。 反幻觉原则: 切勿将猜测当作事实;每项声明都要引用来源;坦率承认不确定性;自行检查输出是否有误;独立交叉核对;对自己的判断保持怀疑——没有证据的确信是所有幻觉的根源。 AI 注意力原则(首因-近因效应): 对于较长的提示词/协议,将最关键的 3 条规则同时放在开头和结尾,以确保指令在较长上下文窗口中仍能得到遵循。 目标驱动执行: 先定义成功标准,循环执行直至验证通过,并且只有在可观察的检查均通过后才停止。 测试验证意图: 测试必须保护业务规则/不变量,并在受保护的意图被破坏时失败,而不能只照搬当前行为。
[LESSON-LEARNED-REMINDER] [BLOCKING] 任务规划与持续改进 — 强制执行。不得跳过。
开始前将工作拆分为小任务并进行跟踪。添加最终任务:"分析 AI 错误与经验教训"。
提取经验教训——仅限根本原因,不处理表面症状:
- 指明失败模式(推理/假设失误),而非症状——例如“未阅读源代码就假设 API 存在”,而不是“使用了错误的枚举值”。
- 通用性测试:此失败模式是否适用于 ≥3 种情境/代码库?如果不适用,就再抽象一层。
- 将其写成通用规则——去除项目特定的名称/路径/类。该规则应适用于任何代码库。
- 合并:多个错误若有相同的失败模式 → 总结为一条经验教训。
- 重复发生检查:“如果没有这条提醒,未来会话中还会发生这种情况吗?”——不会 → 跳过
$learn。 - 自动修复检查:“
$code-review/$code-simplifier/$security/$lint能否发现此问题?”——能 → 改进相应的审查技能。 - 两项检查均通过 → 请用户运行
$learn。 [TASK-PLANNING] [MANDATORY] 在执行任何工作流或技能步骤之前,先为所有计划步骤创建/更新任务跟踪;然后随着每个步骤开始/完成,持续同步任务状态。