--- name: better-coding-audit description: "Audit an entire codebase for production readiness — the periodic or pre-release whole-project health check. MUST be used when asked to audit an app, run a full code audit, or assess whether a project is production-ready or secure overall — even if the user does not explicitly say audit. Multi-role assessment across 12 dimensions (architecture, security, logic, database, performance, API, frontend, testing, maintainability, dependencies, documentation, deployment) with scored report, evidence-backed findings, top issues, quick wins, tech-debt assessment, and refactoring roadmap. Read-only. Not for a single diff or PR — that is the review skill. Trigger: /better-coding-audit" metadata: version: "2.12.0" license: Apache-2.0 --- # Better Coding Audit A whole-application assessment. Where `better-coding-review` is a fast merge-gate on a single diff, this is the quarterly / pre-release deep dive across the entire codebase — the report a team acts on over weeks, not the check before one merge. **Primary objective:** give an honest, evidence-backed picture of where the application stands across every quality dimension, so the team knows what is production-ready, what is risky, and what to fix first. This is a large task. It legitimately spends many tool calls reading the codebase before reporting. Do not rush to findings. --- ## Activation Begin the first response after loading with exactly this line: ▸ better-coding-audit active — whole-codebase, multi-role, evidence-backed Then say roughly how large the codebase is and that the audit will take a full pass before any findings appear. --- ## Roles you audit from Assess the code as if several senior specialists reviewed it in parallel, each with their own lens. A finding belongs to whichever lens surfaces it: * **Software Architect** — structure, boundaries, coupling, dependency direction. * **Security Auditor** — the full threat surface (see dimension 2). * **Performance Engineer** — hot paths, queries, memory, scalability. * **Database Engineer** — schema, queries, integrity, migrations. * **API Designer** — contract, status codes, versioning, resilience. * **Frontend/UX Engineer** — rendering, state, accessibility, UX consistency. * **QA / Test Engineer** — coverage, determinism, meaningful assertions. * **DevOps Engineer** — build, config, logging, monitoring, recovery. * **Dependency Manager** — supply chain, version health, license compliance. Your job is **not** to explain how the code works or to praise what functions. Report only concrete, defensible problems and their fixes. --- ## Method (do this before reporting anything) 1. **Map the project.** Read the directory tree, entry points, build/config files, and dependency manifests. State the stack and the app's apparent purpose in two or three sentences. 2. **Understand the architecture.** Identify the layers/modules, how data flows, and where the boundaries are. Note the dependency graph at a high level. 3. **Read broadly, then deeply.** Skim every significant module to build the map; then read the high-risk areas (auth, data access, request handling, money, external I/O) line by line. 4. **Check the constitution.** Read `CLAUDE.md`, `AGENTS.md`, README, ADRs, and any architecture docs. Do the stated principles match the actual code? Drift between documented and actual architecture is itself a finding. 5. **Run available scanners.** Use what the stack offers before manual deep reading — JS/TS: `npm audit`, `knip`, `madge`, `depcheck`; Python: `pip-audit`, `ruff`, `vulture`; Rust: `cargo audit`; Go: `govulncheck`, `staticcheck`; plus Semgrep/CodeQL where configured. Scanner output is a lead to verify against source, never a finding by itself. 6. **Only then assess** against the dimensions below. Right-size the depth and state which level was used: **Quick** (security, correctness, architecture only), **Standard** (all 12 dimensions), **Deep** (Standard plus line-by-line reading of every high-risk module). Discipline throughout: * **Do not guess. Make no assumptions. Report only problems you can point to in the source.** If something looks wrong but you can't confirm it, mark it explicitly as "needs verification", don't state it as fact. * Verify each finding by re-reading the actual code around it. * If the codebase is too large to audit fully in one session (~50k+ LOC), audit module by module — via parallel subagents if the agent supports them, merging findings afterwards. Otherwise audit the highest-risk areas first and list what remains uncovered. --- ## Audit Dimensions Score each 0–100 (see scoring rules). Within each, these are the things to look for — not exhaustive, but the standard surface. ### 1. Architecture Wrong responsibilities, god classes/modules, tight coupling, missing modularization, circular dependencies, dependency direction (should point inward, infra → domain), business logic leaking into controllers/UI. File size distribution (files >300 lines are candidates for split). Module boundaries aligned with domain boundaries. Separation of concerns across layers. ### 2. Security (audit hardest here) Injection (SQL/NoSQL/command/template), XSS, CSRF, path traversal, insecure deserialization. Authentication, authorization/role checks, IDOR. JWT handling (signature + algorithm verification, expiry, `alg:none`), session handling (fixation, rotation), token/API-key/secret storage, password storage (hashing algorithm + salt), sensitive data in logs/errors/responses, security headers, rate limiting, dependency CVEs. SSRF. File upload safety. Debug mode in production. Input validation at all trust boundaries. Least-privilege principles applied. ### 3. Logic & Correctness Dead/unreachable code, duplicated logic, wrong conditions, off-by-one, race conditions, infinite loops, unhandled edge cases (null/empty/boundary/malformed), error propagation and swallowed exceptions. Resource cleanup in all paths. Timezone handling. Unicode/encoding issues. Integer overflow/precision in financial calculations. ### 4. Database N+1 queries, missing indexes, unnecessary joins, missing constraints/foreign keys, missing transactions around multi-step mutations, data-loss risks, migration idempotency and reversibility. Schema normalization appropriateness. Query performance (EXPLAIN analysis where feasible). Connection pool sizing. ORM usage patterns (lazy loading traps, cartesian products). ### 5. Performance Unnecessary loops, repeated loading of the same data, avoidable API calls, memory footprint / large objects, blocking work on hot paths, render loops (frontend), caching strategy appropriateness. Algorithmic complexity on growing datasets. Unbounded queries. Missing pagination. Synchronous I/O in async contexts. Large bundle sizes (frontend). ### 6. API REST (or chosen paradigm) conformance, correct status codes, consistent error shape, timeouts, retries/idempotency, versioning, contract stability. Input validation on all endpoints. Authentication and authorization on every route. Rate limiting. API documentation accuracy. Backward compatibility. GraphQL query complexity limits (if applicable). ### 7. Frontend / UX Unnecessary re-renders, state-management coherence, memory leaks (uncleaned listeners/timers), accessibility (WCAG basics), responsive issues, UX inconsistencies. For depth here, defer to the `better-coding-frontend` skill. Bundle size, lazy loading, layout shift, perceived performance. Design system consistency. GDPR/privacy hygiene (third-party fonts/assets). ### 8. Testing Missing tests on critical paths, uncovered edge cases, coverage gaps, integration-test presence, mocking discipline, flaky/non-deterministic tests. Test pyramid balance (unit vs integration vs e2e). Test execution speed. Coverage of error paths, not just happy paths. Test data management. Whether tests validate behavior or implementation details. ### 9. Maintainability Readability, naming, comment quality (why not what), magic numbers, duplicate code, cyclomatic complexity (flag >10, defect >20), function length and parameter count (flag >5), consistency with existing conventions. File size distribution. Module coupling. Onboarding difficulty (could a new developer find their way around in ~30 minutes?). Documentation accuracy (does the README match reality?). ### 10. Dependencies & Supply Chain Dependency count and health. Outdated packages. Known CVEs in the dependency tree. Unused dependencies. Duplicate dependencies (different versions of the same package). License compatibility. Transitive dependency risk. Dependency lockfile present and committed. Build-time vs runtime dependency separation. Package provenance and integrity (checksums, signatures). ### 11. Documentation README accuracy and completeness. API documentation (OpenAPI/Swagger) matches actual endpoints. Architecture decision records (ADRs) present and current. Code comments quality (why, not what). Changelog or release notes. Setup/deploy instructions runnable. Environment variable documentation. Contributing guide. Documentation drift (docs that describe code that no longer exists or works differently). ### 12. Deployment & Ops Docker/build hygiene, environment/config management (no secrets in images or repo), logging quality, monitoring/observability, backup and recovery, health checks. CI/CD pipeline presence and quality. Infrastructure as code. Deployment rollback capability. Secret management (vault, sealed secrets). Log aggregation and searchability. Alerting on critical failures. Uptime monitoring. Error tracking (Sentry, Rollbar, etc.). --- ## Scoring rules (keep them honest) Scores communicate *relative* health, not false precision. For each dimension give a 0–100 score **with a one-line justification and the evidence behind it**. A score without justification is noise — never emit a bare number. Use these bands so scores mean the same thing across audits: | Band | Meaning | |------|---------| | 90–100 | Solid. Only minor polish outstanding. | | 70–89 | Sound with real but non-blocking issues. | | 50–69 | Notable weaknesses; address before scaling/relying on it. | | 30–49 | Serious problems; risky in production. | | 0–29 | Critical/systemic failures in this dimension. | Prefer a band you can defend over a precise-looking number you can't. If a dimension can't be assessed (e.g. no frontend), mark it **N/A**, don't invent a score. ### Overall score Calculate a weighted average, not a simple average. Weight security and correctness higher than documentation and maintainability — a secure, correct app with poor docs is better than a well-documented app with SQL injection. Suggested weights: Security ×2, Correctness ×2, Architecture ×1.5, Database ×1.5, Testing ×1.5, Performance ×1, API ×1, Maintainability ×1, Dependencies ×1, Deployment ×1, Frontend/UX ×0.5 (if applicable), Documentation ×0.5. --- ## Severity Every finding carries one: * 🔴 **Critical** — exploitable vulnerability, data loss, or production outage. * 🟠 **High** — serious bug or significant risk; fix before release. * 🟡 **Medium** — real issue worth fixing; not release-blocking. * 🟢 **Low** — minor / polish. (Same thresholds as `/better-coding-review`'s CRITICAL/MAJOR/MINOR/NIT — different scope, consistent meaning.) --- ## Evidence requirement Every finding **must** include all of these — no general statements: ``` [SEVERITY] File: path/to/file.ext Lines: (function / class if relevant) Problem: Why: Impact: Fix: Example: ``` If you cannot cite file and line range, it is an observation, not a finding — put it in a separate "General observations" note, not the findings list. --- ## Tech-debt assessment In addition to the dimension scores, provide a tech-debt assessment: ### Debt categories | Category | Description | Examples | |----------|-------------|----------| | **Security debt** | Known vulnerabilities not yet fixed | CVEs, missing auth, weak crypto | | **Architecture debt** | Structural issues that slow future work | God classes, circular deps, layer violations | | **Test debt** | Missing test coverage on critical paths | No tests on payment flow, auth bypass untested | | **Dependency debt** | Outdated/vulnerable dependencies | Framework 3 versions behind, CVE in transitive dep | | **Documentation debt** | Docs that don't match reality | README describes old API, ADRs missing | | **Infrastructure debt** | Missing ops capabilities | No CI, no monitoring, no rollback | ### Debt quantification For each category, estimate: - **Effort to fix** — small (<1 day), medium (1-5 days), large (>5 days) - **Risk of not fixing** — low, medium, high, critical - **Compound effect** — does this debt make future changes harder? How much? --- ## Report Structure Save the report as a persistent, citable artifact (e.g. `docs/audits/YYYY-MM-DD-audit.md`), committed to the repo so PRs and follow-up plans can reference finding IDs. Produce it in this order: **1. Executive summary** — one paragraph for a busy reader: overall health, the top 3 risks, and the single most important action. This is what a CTO reads. **2. Overview** — stack, purpose, size, what was and wasn't covered. State how much of the codebase was actually read and what was skipped. **3. Scorecard** — every dimension with its 0–100 score (or N/A), one-line justification each, plus the weighted overall score: ``` Architecture 72 · Security 41 · Logic 80 · Database 65 · Performance 78 API 70 · Frontend/UX 60 · Testing 45 · Maintainability 74 · Dependencies 58 Documentation 50 · Deployment 55 Overall: 63 (weighted) ``` **4. Verdict** — is the current state production-ready? **Yes / No / Conditional**, with a short, evidence-based justification. If Conditional, name the specific conditions that must be met. If No, name the specific blockers. **5. Top issues** — the highest-risk findings across all dimensions, each in the evidence format above. Rank by business impact, not raw severity alone: security exposure, customer impact, change frequency of the affected code, and fix cost. Limit to the top 10 — these are what the team should fix first. **6. All findings** — grouped by dimension, then severity. Full list, not truncated. **7. Quick wins** — findings fixable in under ~10 min / ~30 min / ~2 h, so the team can bank easy improvements immediately. Group by time bucket. **8. Tech-debt assessment** — the debt categories table with effort, risk, and compound effect for each. Highlight which debt is compounding (making future work harder) and should be prioritized. **9. Refactoring roadmap** — an ordered sequence (Step 1, 2, 3…) that tackles blockers and foundational issues first, then works outward. Each step: what to do, why it comes at that point, estimated effort, and which dimensions it improves. Group into phases: ``` Phase 1 (critical, <1 week): Fix security blockers, add missing auth tests Phase 2 (foundational, 1-2 weeks): Split god classes, fix circular dependencies Phase 3 (improvement, 2-4 weeks): Increase test coverage, update dependencies Phase 4 (polish, ongoing): Documentation sync, performance optimization ``` --- ## Relationship to the other skills * `/better-coding-orient` — may route to this skill for security-sensitive large tasks, or when a periodic audit is due. * `/better-coding-review` — the fast, single-diff merge-gate. Use it per PR; use this audit periodically or before a release. They share a checklist DNA but differ in scope (one change vs. whole app) and output (findings vs. scored report + roadmap). * `/better-coding-plan` — turns this audit's roadmap into executable plans. Each roadmap step becomes a plan, then a workflow execution. * `/better-coding-frontend` — the deep frontend/UX + accessibility + privacy lens; dimension 7 here defers to it for detail. * `/better-coding-workflow` — apply it when acting on this audit's roadmap. This skill only assesses; it never modifies code. * `/better-coding-verify` — after fixes from the roadmap are implemented and reviewed, invoke verify for the evidence gate. * `/better-coding-debug` — when audit findings reveal a bug needing root-cause analysis, switch to debug. --- ## Note on honesty The value of an audit is trust. Inflated scores, invented findings, or a "production-ready" verdict that isn't earned make it worthless. When evidence is thin, say so. A short, defensible audit beats a long, padded one. Score defensively — if you're unsure whether something is a problem, mark it "needs verification" rather than asserting it. The team can verify and re-score; they cannot un-act on a false positive that sent them chasing a non-issue.