Production Code Audit
Overview
Analyze a codebase to understand its architecture, patterns, and purpose, then produce a detailed audit report with prioritized findings. Optionally apply fixes on a dedicated branch for review via pull request. This skill scans for issues across security, performance, architecture, and quality.
Safety & Workflow
Important: This skill operates in two modes:
- 1. Audit mode (default): Read-only scan that produces a report. No files are modified.
- Fix mode: When the user explicitly requests fixes, create a new branch (e.g.,
audit/production-hardening), apply changes there, and open a draft PR for review. Never push directly to main.
Secrets handling: If hardcoded secrets are discovered, flag them in the report with file and line number. Do NOT remove or commit secrets. Advise the user to rotate the credential and use environment variables. Never log or exfiltrate secret values.
Test execution: Only run tests in a sandboxed or CI environment. Ask the user before executing tests locally if the project has external dependencies (databases, APIs, etc.).
When to Use This Skill
- - Use when user says "audit my codebase" or "make this production-ready"
- Use when preparing for production deployment
- Use when code needs to meet corporate/enterprise standards
How It Works
Step 1: Codebase Discovery
Scan and understand the codebase:
- 1. Read source files - Scan project files (respect .gitignore, skip node_modules/vendor/dist)
- Identify tech stack - Detect languages, frameworks, databases, tools
- Understand architecture - Map out structure, patterns, dependencies
- Identify purpose - Understand what the application does
- Find entry points - Locate main files, routes, controllers
- Map data flow - Understand how data moves through the system
Step 2: Comprehensive Issue Detection
Scan line-by-line for all issues:
Architecture Issues:
- - Circular dependencies
- Tight coupling
- God classes (>500 lines or >20 methods)
- Missing separation of concerns
- Poor module boundaries
- Violation of design patterns
Security Vulnerabilities:
- - SQL injection (string concatenation in queries)
- XSS vulnerabilities (unescaped output)
- Hardcoded secrets (API keys, passwords in code)
- Missing authentication/authorization
- Weak password hashing (MD5, SHA1)
- Missing input validation
- CSRF vulnerabilities
- Insecure dependencies
Performance Problems:
- - N+1 query problems
- Missing database indexes
- Synchronous operations that should be async
- Missing caching
- Inefficient algorithms (O(n²) or worse)
- Large bundle sizes
- Unoptimized images
- Memory leaks
Code Quality Issues:
- - High cyclomatic complexity (>10)
- Code duplication
- Magic numbers
- Poor naming conventions
- Missing error handling
- Inconsistent formatting
- Dead code
- TODO/FIXME comments
Testing Gaps:
- - Missing tests for critical paths
- Low test coverage (<80%)
- No edge case testing
- Flaky tests
- Missing integration tests
Production Readiness:
- - Missing environment variables
- No logging/monitoring
- No error tracking
- Missing health checks
- Incomplete documentation
- No CI/CD pipeline
Step 3: Fixes and Optimizations (Fix Mode Only)
When the user explicitly requests fixes, apply them on a new branch:
CODEBLOCK0
- 1. Refactor architecture - Break up god classes, fix circular dependencies
- Fix security issues - Use parameterized queries, flag secrets for rotation, add validation
- Optimize performance - Fix N+1 queries, add caching, optimize algorithms
- Improve code quality - Reduce complexity, remove duplication, fix naming
- Add missing tests - Write tests for untested critical paths
- Add production infrastructure - Logging, monitoring, health checks
- Optimize everything - Bundle size, images, database queries
- Add documentation - README, API docs, architecture docs
Step 4: Verify and Report
After making all changes:
- 1. Run all tests to ensure nothing broke
- Verify all security issues are fixed
- Measure performance improvements
- Generate comprehensive report
- Provide before/after metrics
Examples
Example 1: Autonomous Codebase Transformation
CODEBLOCK1
Example 2: Automatic Security Hardening
CODEBLOCK2
Example 3: Performance Optimization
CODEBLOCK3
Best Practices
✅ Do This
- - Scan Everything - Read all files, understand entire codebase
- Fix Automatically - Don't just report, actually fix issues
- Prioritize Critical - Security and data loss issues first
- Measure Impact - Show before/after metrics
- Verify Changes - Run tests after making changes
- Be Comprehensive - Cover architecture, security, performance, testing
- Optimize Everything - Bundle size, queries, algorithms, images
- Add Infrastructure - Logging, monitoring, error tracking
- Document Changes - Explain what was fixed and why
❌ Don't Do This
- - Don't Ask Questions - Understand the codebase autonomously
- Don't Wait for Instructions - Scan and fix automatically
- Don't Report Only - Actually make the fixes
- Don't Skip Files - Scan every file in the project
- Don't Ignore Context - Understand what the code does
- Don't Break Things - Verify tests pass after changes
- Don't Be Partial - Fix all issues, not just some
Autonomous Scanning Instructions
When this skill is invoked, automatically:
- 1. Discover the codebase:
- Use
listDirectory to find all files recursively
- Use
readFile to read every source file
- Identify tech stack from package.json, requirements.txt, etc.
- Map out architecture and structure
- 2. Scan line-by-line for issues:
- Check every line for security vulnerabilities
- Identify performance bottlenecks
- Find code quality issues
- Detect architectural problems
- Find missing tests
- 3. Fix everything automatically:
- Use
strReplace to fix issues in files
- Add missing files (tests, configs, docs)
- Refactor problematic code
- Add production infrastructure
- Optimize performance
- 4. Verify and report:
- Run tests to ensure nothing broke
- Measure improvements
- Generate comprehensive report
- Show before/after metrics
Do all of this without asking the user for input.
Common Pitfalls
Problem: Too Many Issues
Symptoms: Team paralyzed by 200+ issues
Solution: Focus on critical/high priority only, create sprints
Problem: False Positives
Symptoms: Flagging non-issues
Solution: Understand context, verify manually, ask developers
Problem: No Follow-Up
Symptoms: Audit report ignored
Solution: Create GitHub issues, assign owners, track in standups
Production Audit Checklist
Security
- - [ ] No SQL injection vulnerabilities
- [ ] No hardcoded secrets
- [ ] Authentication on protected routes
- [ ] Authorization checks implemented
- [ ] Input validation on all endpoints
- [ ] Password hashing with bcrypt (10+ rounds)
- [ ] HTTPS enforced
- [ ] Dependencies have no vulnerabilities
Performance
- - [ ] No N+1 query problems
- [ ] Database indexes on foreign keys
- [ ] Caching implemented
- [ ] API response time < 200ms
- [ ] Bundle size < 200KB (gzipped)
Testing
- - [ ] Test coverage > 80%
- [ ] Critical paths tested
- [ ] Edge cases covered
- [ ] No flaky tests
- [ ] Tests run in CI/CD
Production Readiness
- - [ ] Environment variables configured
- [ ] Error tracking setup (Sentry)
- [ ] Structured logging implemented
- [ ] Health check endpoints
- [ ] Monitoring and alerting
- [ ] Documentation complete
Audit Report Template
CODEBLOCK4
Related Skills
- -
@code-review-checklist - Code review guidelines - INLINECODE5 - API security patterns
- INLINECODE6 - Performance optimization
- INLINECODE7 - Debug production issues
- INLINECODE8 - Architecture patterns
Additional Resources
Pro Tip: Schedule regular audits (quarterly) to maintain code quality. Prevention is cheaper than fixing production bugs!
生产代码审计
概述
分析代码库以理解其架构、模式和用途,然后生成包含优先级排序发现的详细审计报告。可选择在专用分支上应用修复,通过拉取请求进行审查。此技能扫描安全、性能、架构和质量方面的问题。
安全与工作流程
重要提示: 此技能以两种模式运行:
- 1. 审计模式(默认): 只读扫描,生成报告。不修改任何文件。
- 修复模式: 当用户明确请求修复时,创建新分支(例如 audit/production-hardening),在该分支上应用更改,并打开草稿PR以供审查。切勿直接推送到主分支。
机密处理: 如果发现硬编码的机密信息,在报告中标记文件及行号。不要删除或提交机密信息。建议用户轮换凭证并使用环境变量。切勿记录或泄露机密值。
测试执行: 仅在沙箱或CI环境中运行测试。如果项目有外部依赖(数据库、API等),在执行本地测试前询问用户。
何时使用此技能
- - 当用户说审计我的代码库或使其达到生产就绪状态时使用
- 当准备生产部署时使用
- 当代码需要满足企业/公司标准时使用
工作原理
第一步:代码库发现
扫描并理解代码库:
- 1. 读取源文件 - 扫描项目文件(尊重.gitignore,跳过node_modules/vendor/dist)
- 识别技术栈 - 检测语言、框架、数据库、工具
- 理解架构 - 映射结构、模式、依赖关系
- 识别用途 - 理解应用程序的功能
- 查找入口点 - 定位主文件、路由、控制器
- 映射数据流 - 理解数据在系统中的流动方式
第二步:全面问题检测
逐行扫描所有问题:
架构问题:
- - 循环依赖
- 紧耦合
- 上帝类(超过500行或超过20个方法)
- 缺少关注点分离
- 模块边界不清晰
- 违反设计模式
安全漏洞:
- - SQL注入(查询中的字符串拼接)
- XSS漏洞(未转义的输出)
- 硬编码机密(代码中的API密钥、密码)
- 缺少身份验证/授权
- 弱密码哈希(MD5、SHA1)
- 缺少输入验证
- CSRF漏洞
- 不安全的依赖
性能问题:
- - N+1查询问题
- 缺少数据库索引
- 应异步执行的同步操作
- 缺少缓存
- 低效算法(O(n²)或更差)
- 包体积过大
- 未优化的图片
- 内存泄漏
代码质量问题:
- - 高圈复杂度(>10)
- 代码重复
- 魔法数字
- 命名规范差
- 缺少错误处理
- 格式不一致
- 死代码
- TODO/FIXME注释
测试缺口:
- - 关键路径缺少测试
- 测试覆盖率低(<80%)
- 无边界情况测试
- 不稳定测试
- 缺少集成测试
生产就绪性:
- - 缺少环境变量
- 无日志记录/监控
- 无错误追踪
- 缺少健康检查
- 文档不完整
- 无CI/CD流水线
第三步:修复与优化(仅修复模式)
当用户明确请求修复时,在新分支上应用修复:
bash
git checkout -b audit/production-hardening
- 1. 重构架构 - 拆分上帝类,修复循环依赖
- 修复安全问题 - 使用参数化查询,标记需轮换的机密,添加验证
- 优化性能 - 修复N+1查询,添加缓存,优化算法
- 提高代码质量 - 降低复杂度,消除重复,修复命名
- 添加缺失测试 - 为未测试的关键路径编写测试
- 添加生产基础设施 - 日志记录、监控、健康检查
- 全面优化 - 包体积、图片、数据库查询
- 添加文档 - README、API文档、架构文档
第四步:验证与报告
完成所有更改后:
- 1. 运行所有测试以确保没有破坏任何功能
- 验证所有安全问题已修复
- 衡量性能改进
- 生成全面报告
- 提供前后对比指标
示例
示例1:自主代码库转换
markdown
用户:@production-code-audit 使此代码达到生产就绪状态
AI:我将扫描您的整个代码库并将其转换为生产级质量。
第一阶段:发现代码库(分析247个文件)
- - 检测到:Node.js + Express + PostgreSQL + React
- 架构:MVC模式与REST API
- 用途:电商平台
- 入口点:server.js, src/index.tsx
第二阶段:扫描问题(逐行分析)
发现127个问题:
- - 🔴 严重:8个问题
- 🟠 高优先级:23个问题
- 🟡 中优先级:41个问题
- 🔵 低优先级:55个问题
第三阶段:自动修复问题
🔴 严重修复(8/8完成):
- 1. ✅ 修复了UserRepository.findByEmail()中的SQL注入
- 之前:查询中的字符串拼接
- 之后:使用$1占位符的参数化查询
- 2. ✅ 移除了config/database.ts中的硬编码数据库密码
- 之前:password: SuperSecret123!
- 之后:password: process.env.DB_PASSWORD
- 3. ✅ 为管理路由添加了身份验证
- 之前:无身份验证中间件
- 之后:authenticateToken + requireRole(admin)
- 4. ✅ 修复了弱密码哈希(MD5 → bcrypt)
- 之前:crypto.createHash(md5)
- 之后:bcrypt.hash(password, 12)
- 5. ✅ 修复了循环依赖:OrderService ↔ PaymentService
- 之前:直接导入导致循环
- 之后:基于事件的EventBus解耦
- 6. ✅ 为所有API端点添加了输入验证
- 之前:无验证
- 之后:Zod模式验证所有输入
- 7. ✅ 修复了身份验证中间件中的认证绕过
- 之前:缺少token时调用next()
- 之后:返回401错误
- 8. ✅ 修复了UserController中的批量赋值漏洞
- 之前:接受req.body中的所有字段
- 之后:仅允许白名单字段
🟠 高优先级修复(23/23完成):
- 9. ✅ 修复了OrderService.getOrdersWithItems()中的N+1查询
- 之前:循环中的单独查询(2.8秒)
- 之后:带连接的单一查询(45毫秒)
- 性能:提升98%
- 10. ✅ 重构了UserService上帝类(850行 → 4个专注服务)
- UserAuthenticationService(登录、注销、密码)
- UserProfileService(CRUD操作)
- UserNotificationService(邮件、短信)
- UserPermissionService(角色、权限)
- 11. ✅ 为产品查询添加了Redis缓存
- 之前:每次请求都查询数据库
- 之后:1小时TTL的缓存
- 性能:提升95%
- 12. ✅ 优化了包体积
- 之前:850KB(gzip后:280KB)
- 之后:380KB(gzip后:120KB)
- 改进:减少55%
- 13. ✅ 添加了数据库索引
- orders(user
id, status, createdat)
- products(category, price)
- 查询性能:提升98%
[... 另外11个高优先级修复 ...]
🟡 中优先级修复(41/41完成):
[... 所有中优先级修复 ...]
🔵 低优先级改进(55/55完成):
[... 所有低优先级改进 ...]
第四阶段:添加生产基础设施
✅ 添加了结构化日志记录(Winston)
✅ 添加了错误追踪(Sentry)
✅ 添加了健康检查端点(/health, /ready)
✅ 添加了监控(Prometheus指标)
✅ 添加了速率限制(基于Redis)
✅ 添加了API文档(Swagger/OpenAPI)
✅ 添加了全面的README
✅ 添加了部署指南
✅ 添加了CI/CD流水线(.github/workflows)
第五阶段:验证
✅ 所有测试通过(1,247个测试)
✅ 测试覆盖率:42% → 87%
✅ 安全扫描:0个漏洞
✅ 性能:API响应时间3.2秒 → 180毫秒
✅ 包体积:850KB → 380KB
✅ Lighthouse评分:62 → 94
转换完成
您的代码库现已达到企业级质量的生产就绪状态:
📊 指标:
-