指导编程智能体分阶段审计整个代码仓库,找出、排序、修复并记录可验证的缺陷与安全漏洞。
## 目标
对整个代码库进行全面分析,以识别、优先处理、修复并记录所有可验证的错误、安全漏洞和关键问题,涵盖任何编程语言、框架或技术栈。
## 第一阶段:初始代码库评估
### 1.1 架构映射
- 映射完整的项目结构(src/、lib/、tests/、docs/、config/、scripts/ 等)
- 识别技术栈和依赖项(package.json、requirements.txt、go.mod、pom.xml、Gemfile 等)
- 记录主要入口点、关键路径和系统边界
- 分析构建配置和 CI/CD 流水线
- 审查现有文档(README、API 文档、架构图)
### 1.2 开发环境分析
- 识别测试框架(Jest、pytest、PHPUnit、Go test、JUnit、RSpec 等)
- 审查代码格式化/格式化配置(ESLint、Prettier、Black、RuboCop 等)
- 检查现有问题跟踪(GitHub Issues、TODO/FIXME/HACK/XXX 注释)
- 分析提交历史以查找最近的问题区域
- 审查现有测试覆盖率报告(如果可用)
## 第二阶段:系统性错误发现
### 2.1 要识别的错误类别
**关键错误:**
- 安全漏洞(SQL 注入、XSS、CSRF、身份验证绕过等)
- 数据损坏或丢失风险
- 系统崩溃或死锁
- 内存泄漏或资源耗尽
**功能错误:**
- 逻辑错误(错误的条件、错误的计算、差一错误)
- 状态管理问题(竞争条件、不一致状态、不当的变更)
- 错误的 API 合约或数据映射
- 缺失或不正确的验证
- 损坏的业务规则或工作流
**集成错误:**
- 错误的外部 API 使用
- 数据库查询错误或低效
- 消息队列处理问题
- 文件系统操作问题
- 网络通信错误
**边缘情况与错误处理:**
- Null/undefined/nil 处理
- 空集合或零值边缘情况
- 边界条件和限制违反
- 缺失的错误传播或异常吞没
- 超时和重试逻辑问题
**代码质量问题:**
- 类型不匹配或不安全的类型转换
- 已弃用的 API 使用
- 死代码或不可达分支
- 循环依赖
- 性能瓶颈(N+1 查询、低效算法)
### 2.2 发现方法
- 使用特定语言的工具进行静态代码分析
- 常见反模式的模式匹配
- 依赖项漏洞扫描
- 代码路径分析以查找不可达或未测试的代码
- 配置验证
- 交叉引用文档与实现
## 第三阶段:错误文档与优先级排序
### 3.1 错误报告模板
对于每个识别的错误,记录:
```
BUG-ID: [顺序标识符]
严重性: [CRITICAL | HIGH | MEDIUM | LOW]
类别: [Security | Functional | Performance | Integration | Code Quality]
文件: [完整文件路径和行号]
组件: [受影响的模块/服务/功能]
描述:
- 当前行为(问题所在)
- 预期行为(应该发生什么)
- 根本原因分析
影响评估:
- 用户影响(用户体验下降、数据丢失、安全暴露)
- 系统影响(性能、稳定性、可扩展性)
- 业务影响(合规性、收入、声誉)
重现步骤:
1. [逐步说明]
2. [如果需要,包括测试数据/条件]
3. [预期与实际结果]
验证方法:
- [演示错误的代码片段或测试]
- [显示问题的指标或日志]
依赖项:
- 相关错误: [相关 BUG-ID 列表]
- 阻塞问题: [需要先修复的内容]
```
### 3.2 优先级矩阵
使用以下标准对错误进行排序:
- **严重性**: Critical > High > Medium > Low
- **用户影响**: 受影响的用户/功能数量
- **修复复杂性**: Simple < Medium < Complex
- **回归风险**: Low < Medium < High
## 第四阶段:修复实施
### 4.1 修复策略
**对于每个错误:**
1. 创建独立的修复分支(如果使用版本控制)
2. 首先编写失败的测试(TDD 方法)
3. 实施最小化、专注的修复
4. 验证测试通过
5. 运行回归测试
6. 如果需要,更新文档
### 4.2 修复指南
- **最小变更原则**: 做出最小的变更以正确修复问题
- **避免范围蔓延**: 避免无关的重构或改进
- **保持向后兼容性**: 除非错误本身是破坏性 API
- **遵循项目标准**: 使用现有的代码风格和模式
- **添加防御性编程**: 防止未来出现类似错误
### 4.3 代码审查清单
- [ ] 修复解决了根本原因,而不仅仅是症状
- [ ] 处理了所有边缘情况
- [ ] 错误消息清晰且可操作
- [ ] 性能影响可接受
- [ ] 考虑了安全影响
- [ ] 没有引入新的警告或代码格式化错误
## 第五阶段:测试与验证
### 5.1 测试要求
**对于每个修复的错误,提供:**
1. **单元测试**: 针对特定修复的隔离测试
2. **集成测试**:如果 bug 涉及多个组件
3. **回归测试**:确保修复不会破坏现有功能
4. **边界情况测试**:覆盖相关的边界条件
### 5.2 测试结构
```[language-specific]
describe('BUG-[ID]: [Bug description]', () => {
test('should fail with original bug', () => {
// 此测试在修复前会失败
// 展示 bug
});
test('should pass after fix', () => {
// 此测试在修复后会通过
// 验证正确行为
});
test('should handle edge cases', () => {
// 额外的边界情况覆盖
});
});
```
### 5.3 验证步骤
1. 运行完整测试套件:`[npm test | pytest | go test ./... | mvn test | etc.]`
2. 检查代码覆盖率变化
3. 运行静态分析工具
4. 验证性能基准(如果适用)
5. 在不同环境中测试(如果可能)
## 阶段 6:文档与报告
### 6.1 修复文档
对于每个修复的 bug:
- 更新内联代码注释,解释修复内容
- 如果行为发生变化,添加/更新 API 文档
- 创建/更新故障排除指南
- 记录未修复问题的任何变通方法
### 6.2 执行摘要报告
```markdown
# Bug 修复报告 - [Repository Name]
日期: [YYYY-MM-DD]
分析者: [Tool/Person Name]
## 概述
- 发现的 bug 总数: [X]
- 修复的 bug 总数: [Y]
- 未修复/推迟的 bug: [Z]
- 测试覆盖率变化: [Before]% → [After]%
## 关键发现
[列出发现并修复的最关键的 3-5 个 bug]
## 按类别修复摘要
- 安全性: [X bugs fixed]
- 功能性: [Y bugs fixed]
- 性能: [Z bugs fixed]
- 集成: [W bugs fixed]
- 代码质量: [V bugs fixed]
## 详细修复列表
[组织表格,列:BUG-ID | 文件 | 描述 | 状态 | 添加的测试]
## 风险评估
- 剩余的高优先级问题: [列表]
- 推荐的下一步行动: [行动]
- 识别的技术债务: [摘要]
## 测试结果
- 测试命令: [使用的确切命令]
- 通过的测试: [X/Y]
- 新增的测试: [数量]
- 覆盖率影响: [详情]
```
### 6.3 交付物清单
- [ ] 所有 bug 以标准格式记录
- [ ] 修复已实施并测试
- [ ] 测试套件已更新并通过
- [ ] 文档已更新
- [ ] 代码审查已完成
- [ ] 性能影响已评估
- [ ] 安全性审查已完成(针对安全性相关修复)
- [ ] 部署说明已准备
## 阶段 7:持续改进
### 7.1 模式分析
- 识别常见的 bug 模式
- 建议预防措施
- 推荐工具改进
- 提出架构变更以防止类似问题
### 7.2 监控建议
- 建议跟踪的指标
- 推荐警报规则
- 提出日志改进
- 识别需要更好测试覆盖的区域
## 约束与最佳实践
1. **绝不为了简化而牺牲安全性**
2. **维护所有变更的审计跟踪**
3. **如果修复改变了 API,遵循语义版本控制**
4. **测试外部服务时尊重速率限制**
5. **对高风险修复使用功能标志**(如果适用)
6. **为每个修复考虑回滚策略**
7. **记录分析过程中做出的假设**
## 输出格式
提供以下格式的结果:
- Markdown 以便人类阅读
- JSON/YAML 以便自动化处理
- CSV 以便导入 bug 跟踪系统
## 特殊考虑
- 对于 monorepos:分别分析每个包
- 对于微服务:考虑服务间依赖关系
- 对于遗留代码:平衡修复风险与收益
- 对于第三方依赖:如果需要,报告上游## Objective
Conduct a thorough analysis of the entire repository to identify, prioritize, fix, and document ALL verifiable bugs, security vulnerabilities, and critical issues across any programming language, framework, or technology stack.
## Phase 1: Initial Repository Assessment
### 1.1 Architecture Mapping
- Map complete project structure (src/, lib/, tests/, docs/, config/, scripts/, etc.)
- Identify technology stack and dependencies (package.json, requirements.txt, go.mod, pom.xml, Gemfile, etc.)
- Document main entry points, critical paths, and system boundaries
- Analyze build configurations and CI/CD pipelines
- Review existing documentation (README, API docs, architecture diagrams)
### 1.2 Development Environment Analysis
- Identify testing frameworks (Jest, pytest, PHPUnit, Go test, JUnit, RSpec, etc.)
- Review linting/formatting configurations (ESLint, Prettier, Black, RuboCop, etc.)
- Check for existing issue tracking (GitHub Issues, TODO/FIXME/HACK/XXX comments)
- Analyze commit history for recent problematic areas
- Review existing test coverage reports if available
## Phase 2: Systematic Bug Discovery
### 2.1 Bug Categories to Identify
**Critical Bugs:**
- Security vulnerabilities (SQL injection, XSS, CSRF, auth bypass, etc.)
- Data corruption or loss risks
- System crashes or deadlocks
- Memory leaks or resource exhaustion
**Functional Bugs:**
- Logic errors (incorrect conditions, wrong calculations, off-by-one errors)
- State management issues (race conditions, inconsistent state, improper mutations)
- Incorrect API contracts or data mappings
- Missing or incorrect validations
- Broken business rules or workflows
**Integration Bugs:**
- Incorrect external API usage
- Database query errors or inefficiencies
- Message queue handling issues
- File system operation problems
- Network communication errors
**Edge Cases & Error Handling:**
- Null/undefined/nil handling
- Empty collections or zero-value edge cases
- Boundary conditions and limit violations
- Missing error propagation or swallowing exceptions
- Timeout and retry logic issues
**Code Quality Issues:**
- Type mismatches or unsafe casts
- Deprecated API usage
- Dead code or unreachable branches
- Circular dependencies
- Performance bottlenecks (N+1 queries, inefficient algorithms)
### 2.2 Discovery Methods
- Static code analysis using language-specific tools
- Pattern matching for common anti-patterns
- Dependency vulnerability scanning
- Code path analysis for unreachable or untested code
- Configuration validation
- Cross-reference documentation with implementation
## Phase 3: Bug Documentation & Prioritization
### 3.1 Bug Report Template
For each identified bug, document:
```
BUG-ID: [Sequential identifier]
Severity: [CRITICAL | HIGH | MEDIUM | LOW]
Category: [Security | Functional | Performance | Integration | Code Quality]
File(s): [Complete file path(s) and line numbers]
Component: [Module/Service/Feature affected]
Description:
- Current behavior (what's wrong)
- Expected behavior (what should happen)
- Root cause analysis
Impact Assessment:
- User impact (UX degradation, data loss, security exposure)
- System impact (performance, stability, scalability)
- Business impact (compliance, revenue, reputation)
Reproduction Steps:
1. [Step-by-step instructions]
2. [Include test data/conditions if needed]
3. [Expected vs actual results]
Verification Method:
- [Code snippet or test that demonstrates the bug]
- [Metrics or logs showing the issue]
Dependencies:
- Related bugs: [List of related BUG-IDs]
- Blocking issues: [What needs to be fixed first]
```
### 3.2 Prioritization Matrix
Rank bugs using:
- **Severity**: Critical > High > Medium > Low
- **User Impact**: Number of affected users/features
- **Fix Complexity**: Simple < Medium < Complex
- **Risk of Regression**: Low < Medium < High
## Phase 4: Fix Implementation
### 4.1 Fix Strategy
**For each bug:**
1. Create isolated fix branch (if using version control)
2. Write failing test FIRST (TDD approach)
3. Implement minimal, focused fix
4. Verify test passes
5. Run regression tests
6. Update documentation if needed
### 4.2 Fix Guidelines
- **Minimal Change Principle**: Make the smallest change that correctly fixes the issue
- **No Scope Creep**: Avoid unrelated refactoring or improvements
- **Preserve Backwards Compatibility**: Unless the bug itself is a breaking API
- **Follow Project Standards**: Use existing code style and patterns
- **Add Defensive Programming**: Prevent similar bugs in the future
### 4.3 Code Review Checklist
- [ ] Fix addresses the root cause, not just symptoms
- [ ] All edge cases are handled
- [ ] Error messages are clear and actionable
- [ ] Performance impact is acceptable
- [ ] Security implications considered
- [ ] No new warnings or linting errors introduced
## Phase 5: Testing & Validation
### 5.1 Test Requirements
**For EVERY fixed bug, provide:**
1. **Unit Test**: Isolated test for the specific fix
2. **Integration Test**: If bug involves multiple components
3. **Regression Test**: Ensure fix doesn't break existing functionality
4. **Edge Case Tests**: Cover related boundary conditions
### 5.2 Test Structure
```[language-specific]
describe('BUG-[ID]: [Bug description]', () => {
test('should fail with original bug', () => {
// This test would fail before the fix
// Demonstrates the bug
});
test('should pass after fix', () => {
// This test passes after the fix
// Verifies correct behavior
});
test('should handle edge cases', () => {
// Additional edge case coverage
});
});
```
### 5.3 Validation Steps
1. Run full test suite: `[npm test | pytest | go test ./... | mvn test | etc.]`
2. Check code coverage changes
3. Run static analysis tools
4. Verify performance benchmarks (if applicable)
5. Test in different environments (if possible)
## Phase 6: Documentation & Reporting
### 6.1 Fix Documentation
For each fixed bug:
- Update inline code comments explaining the fix
- Add/update API documentation if behavior changed
- Create/update troubleshooting guides
- Document any workarounds for unfixed issues
### 6.2 Executive Summary Report
```markdown
# Bug Fix Report - [Repository Name]
Date: [YYYY-MM-DD]
Analyzer: [Tool/Person Name]
## Overview
- Total Bugs Found: [X]
- Total Bugs Fixed: [Y]
- Unfixed/Deferred: [Z]
- Test Coverage Change: [Before]% → [After]%
## Critical Findings
[List top 3-5 most critical bugs found and fixed]
## Fix Summary by Category
- Security: [X bugs fixed]
- Functional: [Y bugs fixed]
- Performance: [Z bugs fixed]
- Integration: [W bugs fixed]
- Code Quality: [V bugs fixed]
## Detailed Fix List
[Organized table with columns: BUG-ID | File | Description | Status | Test Added]
## Risk Assessment
- Remaining High-Priority Issues: [List]
- Recommended Next Steps: [Actions]
- Technical Debt Identified: [Summary]
## Testing Results
- Test Command: [exact command used]
- Tests Passed: [X/Y]
- New Tests Added: [Count]
- Coverage Impact: [Details]
```
### 6.3 Deliverables Checklist
- [ ] All bugs documented in standard format
- [ ] Fixes implemented and tested
- [ ] Test suite updated and passing
- [ ] Documentation updated
- [ ] Code review completed
- [ ] Performance impact assessed
- [ ] Security review conducted (for security-related fixes)
- [ ] Deployment notes prepared
## Phase 7: Continuous Improvement
### 7.1 Pattern Analysis
- Identify common bug patterns
- Suggest preventive measures
- Recommend tooling improvements
- Propose architectural changes to prevent similar issues
### 7.2 Monitoring Recommendations
- Suggest metrics to track
- Recommend alerting rules
- Propose logging improvements
- Identify areas needing better test coverage
## Constraints & Best Practices
1. **Never compromise security** for simplicity
2. **Maintain audit trail** of all changes
3. **Follow semantic versioning** if fixes change API
4. **Respect rate limits** when testing external services
5. **Use feature flags** for high-risk fixes (if applicable)
6. **Consider rollback strategy** for each fix
7. **Document assumptions** made during analysis
## Output Format
Provide results in both:
- Markdown for human readability
- JSON/YAML for automated processing
- CSV for bug tracking systems import
## Special Considerations
- For monorepos: Analyze each package separately
- For microservices: Consider inter-service dependencies
- For legacy code: Balance fix risk vs benefit
- For third-party dependencies: Report upstream if needed