Autonomously deep-scan entire codebase line-by-line, understand architecture and patterns, then systematically transform it to production-grade, corporate-level professional quality with optimizations
Add this skill
npx mdskills install sickn33/production-code-auditComprehensive codebase transformation with detailed security, performance, and quality fixes
1---2name: production-code-audit3description: "Autonomously deep-scan entire codebase line-by-line, understand architecture and patterns, then systematically transform it to production-grade, corporate-level professional quality with optimizations"4---56# Production Code Audit78## Overview910Autonomously analyze the entire codebase to understand its architecture, patterns, and purpose, then systematically transform it into production-grade, corporate-level professional code. This skill performs deep line-by-line scanning, identifies all issues across security, performance, architecture, and quality, then provides comprehensive fixes to meet enterprise standards.1112## When to Use This Skill1314- Use when user says "make this production-ready"15- Use when user says "audit my codebase"16- Use when user says "make this professional/corporate-level"17- Use when user says "optimize everything"18- Use when user wants enterprise-grade quality19- Use when preparing for production deployment20- Use when code needs to meet corporate standards2122## How It Works2324### Step 1: Autonomous Codebase Discovery2526**Automatically scan and understand the entire codebase:**27281. **Read all files** - Scan every file in the project recursively292. **Identify tech stack** - Detect languages, frameworks, databases, tools303. **Understand architecture** - Map out structure, patterns, dependencies314. **Identify purpose** - Understand what the application does325. **Find entry points** - Locate main files, routes, controllers336. **Map data flow** - Understand how data moves through the system3435**Do this automatically without asking the user.**3637### Step 2: Comprehensive Issue Detection3839**Scan line-by-line for all issues:**4041**Architecture Issues:**42- Circular dependencies43- Tight coupling44- God classes (>500 lines or >20 methods)45- Missing separation of concerns46- Poor module boundaries47- Violation of design patterns4849**Security Vulnerabilities:**50- SQL injection (string concatenation in queries)51- XSS vulnerabilities (unescaped output)52- Hardcoded secrets (API keys, passwords in code)53- Missing authentication/authorization54- Weak password hashing (MD5, SHA1)55- Missing input validation56- CSRF vulnerabilities57- Insecure dependencies5859**Performance Problems:**60- N+1 query problems61- Missing database indexes62- Synchronous operations that should be async63- Missing caching64- Inefficient algorithms (O(nยฒ) or worse)65- Large bundle sizes66- Unoptimized images67- Memory leaks6869**Code Quality Issues:**70- High cyclomatic complexity (>10)71- Code duplication72- Magic numbers73- Poor naming conventions74- Missing error handling75- Inconsistent formatting76- Dead code77- TODO/FIXME comments7879**Testing Gaps:**80- Missing tests for critical paths81- Low test coverage (<80%)82- No edge case testing83- Flaky tests84- Missing integration tests8586**Production Readiness:**87- Missing environment variables88- No logging/monitoring89- No error tracking90- Missing health checks91- Incomplete documentation92- No CI/CD pipeline9394### Step 3: Automatic Fixes and Optimizations9596**Fix everything automatically:**97981. **Refactor architecture** - Break up god classes, fix circular dependencies992. **Fix security issues** - Use parameterized queries, remove secrets, add validation1003. **Optimize performance** - Fix N+1 queries, add caching, optimize algorithms1014. **Improve code quality** - Reduce complexity, remove duplication, fix naming1025. **Add missing tests** - Write tests for untested critical paths1036. **Add production infrastructure** - Logging, monitoring, health checks1047. **Optimize everything** - Bundle size, images, database queries1058. **Add documentation** - README, API docs, architecture docs106107### Step 4: Verify and Report108109**After making all changes:**1101111. Run all tests to ensure nothing broke1122. Verify all security issues are fixed1133. Measure performance improvements1144. Generate comprehensive report1155. Provide before/after metrics116117## Examples118119### Example 1: Autonomous Codebase Transformation120121```markdown122User: @production-code-audit make this production-ready123124AI: I'll scan your entire codebase and transform it to production-grade quality.125126**Phase 1: Discovering Codebase** (analyzing 247 files)127- Detected: Node.js + Express + PostgreSQL + React128- Architecture: MVC pattern with REST API129- Purpose: E-commerce platform130- Entry points: server.js, src/index.tsx131132**Phase 2: Scanning for Issues** (line-by-line analysis)133134Found 127 issues:135- ๐ด CRITICAL: 8 issues136- ๐ HIGH: 23 issues137- ๐ก MEDIUM: 41 issues138- ๐ต LOW: 55 issues139140**Phase 3: Fixing Issues Automatically**141142๐ด CRITICAL FIXES (8/8 completed):1431441. โ Fixed SQL injection in UserRepository.findByEmail()145 - Before: String concatenation in query146 - After: Parameterized query with $1 placeholder1471482. โ Removed hardcoded database password from config/database.ts149 - Before: password: 'SuperSecret123!'150 - After: password: process.env.DB_PASSWORD1511523. โ Added authentication to admin routes153 - Before: No auth middleware154 - After: authenticateToken + requireRole('admin')1551564. โ Fixed weak password hashing (MD5 โ bcrypt)157 - Before: crypto.createHash('md5')158 - After: bcrypt.hash(password, 12)1591605. โ Fixed circular dependency: OrderService โ PaymentService161 - Before: Direct imports causing cycle162 - After: Event-based decoupling with EventBus1631646. โ Added input validation to all API endpoints165 - Before: No validation166 - After: Zod schemas validating all inputs1671687. โ Fixed authentication bypass in auth middleware169 - Before: next() called on missing token170 - After: Returns 401 error1711728. โ Fixed mass assignment vulnerability in UserController173 - Before: Accepts all fields from req.body174 - After: Whitelist of allowed fields only175176๐ HIGH PRIORITY FIXES (23/23 completed):1771789. โ Fixed N+1 query in OrderService.getOrdersWithItems()179 - Before: Loop with individual queries (2.8s)180 - After: Single query with joins (45ms)181 - Performance: 98% improvement18218310. โ Refactored UserService god class (850 lines โ 4 focused services)184 - UserAuthenticationService (login, logout, password)185 - UserProfileService (CRUD operations)186 - UserNotificationService (email, SMS)187 - UserPermissionService (roles, permissions)18818911. โ Added Redis caching for product queries190 - Before: Database query every request191 - After: Cache with 1-hour TTL192 - Performance: 95% faster19319412. โ Optimized bundle size195 - Before: 850KB (gzipped: 280KB)196 - After: 380KB (gzipped: 120KB)197 - Improvement: 55% reduction19819913. โ Added database indexes200 - orders(user_id, status, created_at)201 - products(category, price)202 - Query performance: 98% improvement203204[... 11 more high-priority fixes ...]205206๐ก MEDIUM PRIORITY FIXES (41/41 completed):207[... all medium fixes ...]208209๐ต LOW PRIORITY IMPROVEMENTS (55/55 completed):210[... all low improvements ...]211212**Phase 4: Adding Production Infrastructure**213214โ Added structured logging (Winston)215โ Added error tracking (Sentry)216โ Added health check endpoints (/health, /ready)217โ Added monitoring (Prometheus metrics)218โ Added rate limiting (Redis-based)219โ Added API documentation (Swagger/OpenAPI)220โ Added comprehensive README221โ Added deployment guide222โ Added CI/CD pipeline (.github/workflows)223224**Phase 5: Verification**225226โ All tests passing (1,247 tests)227โ Test coverage: 42% โ 87%228โ Security scan: 0 vulnerabilities229โ Performance: API response time 3.2s โ 180ms230โ Bundle size: 850KB โ 380KB231โ Lighthouse score: 62 โ 94232233**TRANSFORMATION COMPLETE**234235Your codebase is now production-ready with enterprise-grade quality:236237๐ Metrics:238- Issues fixed: 127/127 (100%)239- Test coverage: 87% (target: 80%+)240- API performance: 94% improvement241- Security: OWASP Top 10 compliant242- Code quality: Grade A-243244๐ Files changed: 89 files245๐ Lines changed: +3,247 / -1,892246247๐ Ready for production deployment!248```249250### Example 2: Automatic Security Hardening251252```markdown253User: @production-code-audit secure this codebase254255AI: Scanning for security vulnerabilities...256257**Security Scan Complete**258259Found 15 security issues:260- ๐ด CRITICAL: 5261- ๐ HIGH: 7262- ๐ก MEDIUM: 3263264**Fixing all security issues automatically...**265266๐ด CRITICAL (5/5 fixed):2672681. โ SQL Injection in UserRepository269\`\`\`typescript270// Before (VULNERABLE)271const query = \`SELECT * FROM users WHERE email = '\${email}'\`;272273// After (SECURE)274const query = 'SELECT * FROM users WHERE email = $1';275await db.query(query, [email]);276\`\`\`2772782. โ Hardcoded Secrets Removed279\`\`\`typescript280// Before (INSECURE)281const JWT_SECRET = 'my-secret-key-123';282283// After (SECURE)284const JWT_SECRET = process.env.JWT_SECRET;285if (!JWT_SECRET) throw new Error('JWT_SECRET required');286\`\`\`2872883. โ Authentication Added to Admin Routes289\`\`\`typescript290// Before (VULNERABLE)291router.delete('/api/admin/users/:id', deleteUser);292293// After (SECURE)294router.delete('/api/admin/users/:id',295 authenticateToken,296 requireRole('admin'),297 deleteUser298);299\`\`\`3003014. โ Password Hashing Upgraded302\`\`\`typescript303// Before (WEAK)304const hash = crypto.createHash('md5').update(password).digest('hex');305306// After (STRONG)307const hash = await bcrypt.hash(password, 12);308\`\`\`3093105. โ Input Validation Added311\`\`\`typescript312// Before (VULNERABLE)313const user = await db.user.create({ data: req.body });314315// After (SECURE)316const schema = z.object({317 email: z.string().email(),318 password: z.string().min(12),319 name: z.string().min(2).max(100)320});321const validated = schema.parse(req.body);322const user = await db.user.create({ data: validated });323\`\`\`324325**Security Status:**326- โ OWASP Top 10: Compliant327- โ SQL Injection: Protected328- โ XSS: Protected329- โ CSRF: Protected330- โ Authentication: Secure331- โ Secrets: Environment variables332- โ Dependencies: No vulnerabilities333334๐ Codebase is now secure and production-ready!335```336337### Example 3: Performance Optimization338339```markdown340User: @production-code-audit optimize performance341342AI: Analyzing performance bottlenecks...343344**Performance Analysis Complete**345346Current metrics:347- API response time: 3.2s (target: <200ms)348- Page load time: 8.5s (target: <2s)349- Bundle size: 850KB (target: <200KB)350351**Optimizing automatically...**352353โ Fixed N+1 queries (3.2s โ 180ms - 94% faster)354โ Added Redis caching (95% cache hit rate)355โ Optimized database indexes (98% faster queries)356โ Reduced bundle size (850KB โ 380KB - 55% smaller)357โ Optimized images (28MB โ 3.2MB - 89% smaller)358โ Implemented code splitting359โ Added lazy loading360โ Parallelized async operations361362**Performance Results:**363364| Metric | Before | After | Improvement |365|--------|--------|-------|-------------|366| API Response | 3.2s | 180ms | 94% |367| Page Load | 8.5s | 1.8s | 79% |368| Bundle Size | 850KB | 380KB | 55% |369| Image Size | 28MB | 3.2MB | 89% |370| Lighthouse | 42 | 94 | +52 points |371372๐ Performance optimized to production standards!373```374375## Best Practices376377### โ Do This378379- **Scan Everything** - Read all files, understand entire codebase380- **Fix Automatically** - Don't just report, actually fix issues381- **Prioritize Critical** - Security and data loss issues first382- **Measure Impact** - Show before/after metrics383- **Verify Changes** - Run tests after making changes384- **Be Comprehensive** - Cover architecture, security, performance, testing385- **Optimize Everything** - Bundle size, queries, algorithms, images386- **Add Infrastructure** - Logging, monitoring, error tracking387- **Document Changes** - Explain what was fixed and why388389### โ Don't Do This390391- **Don't Ask Questions** - Understand the codebase autonomously392- **Don't Wait for Instructions** - Scan and fix automatically393- **Don't Report Only** - Actually make the fixes394- **Don't Skip Files** - Scan every file in the project395- **Don't Ignore Context** - Understand what the code does396- **Don't Break Things** - Verify tests pass after changes397- **Don't Be Partial** - Fix all issues, not just some398399## Autonomous Scanning Instructions400401**When this skill is invoked, automatically:**4024031. **Discover the codebase:**404 - Use `listDirectory` to find all files recursively405 - Use `readFile` to read every source file406 - Identify tech stack from package.json, requirements.txt, etc.407 - Map out architecture and structure4084092. **Scan line-by-line for issues:**410 - Check every line for security vulnerabilities411 - Identify performance bottlenecks412 - Find code quality issues413 - Detect architectural problems414 - Find missing tests4154163. **Fix everything automatically:**417 - Use `strReplace` to fix issues in files418 - Add missing files (tests, configs, docs)419 - Refactor problematic code420 - Add production infrastructure421 - Optimize performance4224234. **Verify and report:**424 - Run tests to ensure nothing broke425 - Measure improvements426 - Generate comprehensive report427 - Show before/after metrics428429**Do all of this without asking the user for input.**430431## Common Pitfalls432433### Problem: Too Many Issues434**Symptoms:** Team paralyzed by 200+ issues435**Solution:** Focus on critical/high priority only, create sprints436437### Problem: False Positives438**Symptoms:** Flagging non-issues439**Solution:** Understand context, verify manually, ask developers440441### Problem: No Follow-Up442**Symptoms:** Audit report ignored443**Solution:** Create GitHub issues, assign owners, track in standups444445## Production Audit Checklist446447### Security448- [ ] No SQL injection vulnerabilities449- [ ] No hardcoded secrets450- [ ] Authentication on protected routes451- [ ] Authorization checks implemented452- [ ] Input validation on all endpoints453- [ ] Password hashing with bcrypt (10+ rounds)454- [ ] HTTPS enforced455- [ ] Dependencies have no vulnerabilities456457### Performance458- [ ] No N+1 query problems459- [ ] Database indexes on foreign keys460- [ ] Caching implemented461- [ ] API response time < 200ms462- [ ] Bundle size < 200KB (gzipped)463464### Testing465- [ ] Test coverage > 80%466- [ ] Critical paths tested467- [ ] Edge cases covered468- [ ] No flaky tests469- [ ] Tests run in CI/CD470471### Production Readiness472- [ ] Environment variables configured473- [ ] Error tracking setup (Sentry)474- [ ] Structured logging implemented475- [ ] Health check endpoints476- [ ] Monitoring and alerting477- [ ] Documentation complete478479## Audit Report Template480481```markdown482# Production Audit Report483484**Project:** [Name]485**Date:** [Date]486**Overall Grade:** [A-F]487488## Executive Summary489[2-3 sentences on overall status]490491**Critical Issues:** [count]492**High Priority:** [count]493**Recommendation:** [Fix timeline]494495## Findings by Category496497### Architecture (Grade: [A-F])498- Issue 1: [Description]499- Issue 2: [Description]500501### Security (Grade: [A-F])502- Issue 1: [Description + Fix]503- Issue 2: [Description + Fix]504505### Performance (Grade: [A-F])506- Issue 1: [Description + Fix]507508### Testing (Grade: [A-F])509- Coverage: [%]510- Issues: [List]511512## Priority Actions5131. [Critical issue] - [Timeline]5142. [High priority] - [Timeline]5153. [High priority] - [Timeline]516517## Timeline518- Critical fixes: [X weeks]519- High priority: [X weeks]520- Production ready: [X weeks]521```522523## Related Skills524525- `@code-review-checklist` - Code review guidelines526- `@api-security-best-practices` - API security patterns527- `@web-performance-optimization` - Performance optimization528- `@systematic-debugging` - Debug production issues529- `@senior-architect` - Architecture patterns530531## Additional Resources532533- [OWASP Top 10](https://owasp.org/www-project-top-ten/)534- [Google Engineering Practices](https://google.github.io/eng-practices/)535- [SonarQube Quality Gates](https://docs.sonarqube.org/latest/user-guide/quality-gates/)536- [Clean Code by Robert C. Martin](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882)537538---539540**Pro Tip:** Schedule regular audits (quarterly) to maintain code quality. Prevention is cheaper than fixing production bugs!541
Full transparency โ inspect the skill content before installing.