AI coding tools are working. Teams that leverage agentic development generate more code, open more pull requests, and move from idea to implementation faster than ever. The open question for engineering leadership is whether that output is durable: fewer defects, less rework, and code that holds up in production.
Answering that question takes more than counting generated lines or tracking a single pass rate. This guide covers the AI code quality metrics that matter, and how to calculate them with explicit denominators. It explains where the data comes from, how to interpret results without overclaiming, and how to build a scorecard your engineering org can act on. It closes with what SonarQube measures directly and what requires integrating with data from other systems.
Which AI code quality metrics should you track?
Track two layers together. Code-level metrics describe the health of the code itself. Process and outcome metrics describe whether verification happened and whether the code held up after merge. Neither layer is complete alone.
Verification coverage and first-pass quality are process measures. They tell you that checks ran and what they found. They do not prove the code is correct. Pair them with code-level and outcome metrics, so a rising pass rate never stands in for code quality.
Should AI-generated code be held to the same quality standards?
Code health, including code quality and code security standards, should not change based on who or what wrote the code. A null pointer dereference, an injection flaw, or a 400-line function carry the same risk regardless of origin. Hold every change to one standard, and you get comparable data and a single, defensible policy.
Define the unit of analysis first
Every metric needs a clear unit. Pick one per metric and keep it consistent across periods:
- Change or commit: Best for code-level findings and rework attribution.
- Pull request (PR): Best for verification coverage, first-pass quality, review time, and cycle time.
- Repository or project: Best for debt trends, coverage trends, and policy compliance.
- Deployment: Best for change failure rate.
- Incident: Best for recovery time and escaped-defect impact.
Mixing units produces misleading ratios. A rework rate calculated per commit is not comparable to one calculated per PR.
How to properly identify authorship
Reliable provenance comes from explicit signals: AI tool telemetry, agent-created PR labels, commit trailers, or branch naming conventions your platform engineering team enforces. When those signals are missing, classify the change as unknown. Never infer authorship from code style. Style-based guesses introduce bias and undermine every comparison built on them.
Why track code health instead of just AI-generated volume?
More code is not better code. Generated volume measures throughput, and throughput without code health creates verification debt that your team must pay down in future releases. Code-level metrics show whether the code entering your codebase meets your standards.
New-code findings and severity
Definition: Issues introduced by changes within a defined new-code period or PR, grouped by software quality (reliability, security, maintainability) and severity.
Formula: New-code issue density = new issues ÷ new or changed lines × 1,000
Source: Code analysis results on each PR and branch.
Limitation: The discovered issues from analysis isn’t enough on its own. Track how many findings developers fix, accept, or mark as false positives. A high fix rate on high-severity findings is a strong quality signal. A high dismissal rate points to a ruleset that needs tuning.
Security findings
Definition: Security vulnerabilities covering confirmed risky patterns and code that requires review to determine risk, reported on new code.
Formula: Security vulnerability review rate = security vulnerabilities reviewed ÷ security vulnerabilities raised on new code × 100
Limitation: Security vulnerabilities cover confirmed risky patterns and code that requires review to determine risk. Track how many findings developers fix, accept, or mark as false positives. A high fix rate on high-severity findings is a strong quality signal. A high dismissal rate points to a ruleset that needs tuning.
Cognitive Complexity
Definition: How complex code is to understand by a human.
Formula: Cognitive complexity is a proprietary Sonar measurement. Read the white paper on how Sonar calculates it.
Why it matters for AI-generated code: AI generates more verbose code than humans. Even as agents become more advanced, the number of lines they generate to solve a problem increases. After all, an agent's objective is to solve a problem and not make code that’s easy for humans to understand. As code becomes more difficult to understand, it becomes increasingly less maintainable.
Cyclomatic Complexity
Definition: A calculation of the number of paths through the code.
Formula: 1 + number of conditional branches
Why it matters for AI-generated code: AI generates more lines of code than human written code to solve the same problems, increasing the cyclomatic complexity of codebases. A lower cyclomatic complexity indicates a simpler control flow with fewer branches and independent branches. As cyclomatic complexity increases, code becomes more difficult to understand and maintain. Read more details about cyclomatic complexity.
Duplications
Definition: The portion of code that contains duplicate lines. This calculation can be performed on overall code, as well as a measurement on new code.
Formula: Duplicated lines density = number of duplicate lines ÷ total number of lines × 100
Why it matters for AI-generated code: Agents often produce duplicated code in multiple places rather than using more elegant shared abstractions. Rising duplication raises review effort today and maintenance cost next quarter, even when every test passes.
Test coverage
Definition: The portion of code that tests execute. This calculation can be performed on overall code, as well as a measurement on new code.
Formula: Coverage = (number of conditions evaluated to true at least once + number of lines that tests execute) / (total number of conditions + total executable lines of code)
Source: Coverage reports generated by your test framework and imported into analysis.
Limitation: Coverage measures execution, not verification. A test without meaningful assertions raises coverage and catches nothing. AI tools generate tests quickly, so treat coverage as necessary but insufficient. Pair it with escaped defects and, where practical, mutation testing on critical modules.
Technical debt trend
Definition: Estimated remediation effort for maintainability issues, tracked over time.
Formula: Technical debt ratio = estimated remediation cost ÷ estimated development cost of the codebase × 100
Limitation: Remediation estimates are model-based. Use the trend, not the absolute number, and compare it across consistent rulesets.
How do you measure whether verification covers AI-generated code?
Verification is mandatory, not optional. In an agentic software factory, it is also where the bottleneck forms: code arrives faster than teams can confidently review and release it. These metrics show whether verification reaches every change and whether it catches problems before merging.
Verification coverage
Formula: Verification coverage = eligible changes with all required checks completed ÷ eligible changes × 100
Define "eligible" explicitly. For example: all PRs targeting protected branches in production repositories, excluding automated dependency bumps if those follow a separate policy. Define "required checks" as a named, versioned bundle, such as code analysis with a quality gate, unit tests, and code security analysis.
Source: Analysis results per PR, joined with your source control system's list of merged PRs and your CI run records. The denominator comes from source control, not from the analysis tool, because a change that was never analyzed never appears in analysis results.
First-pass quality
Formula: First-pass quality = changes passing the defined check bundle on the first completed run ÷ changes with an evaluatable first run × 100
Exclude runs that failed for infrastructure reasons, such as a CI timeout, from the denominator. Count only the first run that completed and produced a result.
Interpretation: A rising first-pass rate means fewer fix-and-rerun cycles and shorter review loops. It does not mean the code is correct. A rate that climbs right after a ruleset change usually reflects looser checks, not better code.
Bypasses, waivers, and pre-merge resolution
Coverage and pass rates mean little if checks are routinely skipped. Track these alongside them:
- Bypass rate = eligible merged changes where a required check was skipped or overridden ÷ eligible merged changes × 100
- Waiver rate = findings marked "accepted" or "won't fix" on new code ÷ findings raised on new code × 100
- Failed check rate = check runs that failed ÷ completed check runs × 100
- Pre-merge resolution rate = findings raised on a change and fixed before merge ÷ findings raised on changes × 100
A high pre-merge resolution rate is one of the clearest signals that verification is working. It shows problems caught and fixed at the cheapest point in your release cycle.
Version the check bundle
Rules, quality profiles, quality gate conditions, and test suites change. Record a version for the check bundle and note every change in your scorecard. Without versioning, a jump in first-pass quality and a relaxed rule look identical.
How does verification connect to rework and production outcomes?
Code-level health and verification activity matter because they drive delivery outcomes. This layer connects your checks to the results leadership cares about: less rework, faster flow, and fewer production failures.
Rework rate
Formula: Rework rate = merged changes that require a corrective follow-up change within N days ÷ merged changes in the period × 100
State the observation window explicitly (14 or 30 days are common choices) and keep it fixed. Count a follow-up as corrective when it reverts the change, fixes a linked bug, or addresses a defect traced to the change. Exclude routine feature evolution, such as a planned second iteration, wherever your ticket links make that distinction possible.
Review wait time and PR cycle time
- Review wait time: Time from PR marked ready for review to first substantive review.
- PR cycle time: Time from PR opened to PR merged.
Report the median and the 85th percentile, not the mean. A handful of stalled PRs distort averages. If generated volume rises while review wait time grows, your bottleneck has moved to verification, and adding reviewers alone will not clear it.
Escaped defects
Formula: Escaped defect rate = defects found after release and traced to changes in the period ÷ changes released in the period × 100
Define "escaped" consistently: found in staging after sign-off, in production, or by customers. Pick one boundary and keep it.
Change failure rate
Formula: Change failure rate = deployments that degraded service and required remediation ÷ total deployments × 100
Source: Deployment records joined with incident records.
Keep recovery and remediation separate
Two different clocks often get merged into one "MTTR." Keep them apart:
- Failed deployment recovery time: Time from a deployment-caused incident starting to service being restored. An incident-level measure from incident management data.
- Finding-to-fix time: Time from a code finding being raised to its resolution. A code remediation measure from analysis data.
They measure different work, owned by different teams, with different levers. Combining them produces a number nobody can act on.
How do you build a baseline for AI code quality metrics?
Trends need a starting point. Comparisons need groups that are actually comparable. Without both, a dashboard tells a story the data cannot support.
Establish a baseline
- Define a baseline window (for example, the 90 days before broad AI tool rollout) and a follow-up window of equal length.
- Freeze metric definitions, units of analysis, and the check bundle version for the comparison, or document every change.
- Record sample sizes for every metric. A rework rate based on 12 PRs is an anecdote, not a trend.
Compare like with like
Cohorts differ in ways that affect outcomes. Disclose and control for:
- Task mix: New features, bug fixes, refactors, and tests carry different risks.
- Risk level: Payment or authentication code is not comparable to internal tooling.
- Language and framework: Rule coverage and defect patterns vary by language.
- Team and repository: Experience, ownership, and codebase age all shift results.
- Tool and ruleset variations: A different AI model, a different agent configuration and a different quality profile, breaks comparability.
Create a scorecard that leads to action
A scorecard earns its place when every metric has an owner and a defined response. Copy the structure below and fill in values from your own systems. Leave cells blank until you have real data, and do not import universal "healthy" benchmarks. Your baseline is the benchmark.
Add three header fields above the table: check bundle version, baseline and follow-up windows, and provenance method (or "not available"). Those three fields make every row interpretable.
Example response to deterioration (hypothetical): If bypass rate rises above the baseline for two consecutive periods, the platform engineering owner reviews branch protection settings and the list of bypassed PRs within one sprint.
What is the code confidence formula for AI-generated code?
Metrics answer specific questions. A framework tells you whether you are asking the right ones. Sonar organizes them around one idea:
Code confidence = Intent × Guiderails × Verification × Evidence
Because the terms multiply, if any one is zero, confidence is zero. Strong verification cannot compensate for missing intent, and clear intent means little without evidence that the code matches it. Use the formula to check coverage across your scorecard, not to compute a score.
Do not assign ratings to each term and multiply them into a single number. Arbitrary ratings produce a figure that looks precise and carries no validated meaning. The formula's value is structural: it shows you which part of your process lacks measurement.
Sonar's Agent Centric Development Cycle (AC/DC) framework puts the formula to work through three pillars: Guide, Verify, and Solve. Guide sets the guiderails agents work within. Verify checks every change independently. Solve fixes findings and re-verifies each fix before it reaches a reviewer.
How does SonarQube measure AI-generated code quality?
AI generates. SonarQube verifies. SonarQube is the independent code verification layer for AI-generated code and all other code, applying one standard to every change across more than 45 languages. Here is what it measures directly, and where you join its data with other systems.
What SonarQube measures directly
Consistent standards across every change. You hold AI-generated code and all other code to one bar, so comparisons between cohorts reflect the code, not shifting rules. SonarQube applies quality profiles and quality gates to every PR and branch analysis, with a defined new-code period that isolates recent changes.
Accurate code-level findings your teams trust. Developers fix real problems instead of triaging noise, which keeps review cycles short. SonarQube's deterministic and agentic analysis reports reliability, security, and maintainability issues by severity, with a false-positive rate under 3.2%.
Security risk visible before merge. You catch vulnerable patterns while the fix is still cheap and the author still has context. SonarQube's code security analysis reports security vulnerabilities on new code, and SonarQube Advanced Security extends coverage to open-source dependencies and SBOMs.
Maintainability trends you can track over time. Leaders see whether faster generation is adding debt, and teams see where to act. SonarQube reports cognitive and cyclomatic complexity, duplication, technical debt, and technical debt ratio, at the project level and on new code.
Coverage tied to the code that changed. You see whether new code is tested, not just whether the overall percentage moved. SonarQube imports coverage reports from your test frameworks and reports coverage on new code as a quality gate condition.
Verification results in the developer workflow. Developers see findings where they already work, and reviewers spend time on design rather than defects. SonarQube decorates PRs in GitHub, GitLab, Bitbucket, and Azure DevOps with quality gate status and findings.
A stricter standard where you choose to apply one. You raise the bar for AI-generated code without slowing every project. With AI Code Assurance, you mark projects that contain AI-generated code and apply a qualified quality gate to them. You decide which projects to mark; SonarQube does not detect AI authorship on its own.
Fixes that close the loop. Finding a code issue is only half the job. SonarQube Remediation Agent suggests fixes for findings, and developers review them before merge, so pre-merge resolution rates rise without bypassing verification.
Evidence for audits and reporting. Every analysis produces a retained result, so you can show which changes passed which checks. Quality gate history, issue status changes, and quality profile changelogs give you the evidence term in the code confidence formula. The SonarQube Web API exports measures for your own reporting.
What requires joined data
Several scorecard metrics depend on systems outside SonarQube. Plan for these joins in your data pipeline:
- Verification coverage and bypass rate: Require your source control system's list of eligible merged PRs and branch protection records as the denominator.
- First-pass quality: Combines SonarQube quality gate results with CI run history to identify the first completed run.
- Provenance segmentation: Requires AI tool telemetry, PR labels, or commit conventions.
- Rework, review wait time, and PR cycle time: Come from source control and issue tracker data.
- Escaped defects, change failure rate, and recovery time: Come from issue tracking, deployment, and incident management systems.
SonarQube supplies the code-level and verification signals for each change. Your analytics or engineering intelligence tooling joins those signals with delivery and incident data to complete the scorecard.
Next step: Assess your verification coverage
Code is abundant. Confidence is scarce. Start by measuring how much of your code actually passes through verification today. Pick one production repository, count eligible PRs from the last 90 days, and check how many completed every required check. That single number tells you where your scorecard starts.
Assess your verification coverage and explore how SonarQube measures code quality across every change.
