By NHI Mgmt Group Editorial TeamBased on Sonar: “Your AI bill is a code quality problem” (June 17, 2026)

TL;DR: Cleaner code reduced Claude Code usage by 7.1% fewer input tokens, 8.5% fewer output tokens, and 11.1% less reasoning effort, while pass rates stayed effectively unchanged, according to Sonar’s controlled study. The finding matters because code structure now influences both developer productivity and AI operating cost, turning maintainability into a FinOps and governance issue.


At a glance

What this is: Sonar’s controlled study found that cleaner code lowered Claude Code’s token use and reasoning effort while pass rates stayed effectively unchanged.

Why it matters: For IAM, NHI and engineering governance teams, code maintainability is no longer only a developer experience issue because it now shapes the cost and operational footprint of AI coding agents.

By the numbers:

  • Agents working on cleaner code used 7.1% fewer input tokens, 8.5% fewer output tokens, and 11.1% less reasoning effort.
  • The study found a less than 1% difference in pass rate between cleaner and messier repositories.
  • On one commons-bcel task, the cleaned version used 35% fewer input tokens and opened 25% fewer files.
  • DX research cited in the article found that more than 400 engineering organizations now spend $200 to $600 per engineer per month on mixed coding tools.

Context

AI coding agents consume tokens in proportion to how hard code is to navigate, not just how much code exists. Dense control flow, unclear names and tangled module boundaries make the agent reread more, plan longer and send larger context windows on each turn, which turns maintainability into a usage-cost problem as well as a code-quality problem.

That matters for identity and governance programmes because agentic coding tools are becoming part of the software delivery chain, not just a developer convenience. When an AI agent repeatedly traverses the same repository, the organisation inherits a new operational dependency: code structure now influences spend, delivery efficiency and the control burden around how much agent work is acceptable in production engineering workflows.

Sonar’s study is particularly useful because it separates structural quality from the underlying application and test suite. By holding the application constant and changing only the code’s internal shape, it shows that cleaner structure can reduce the cost of agent interaction even when functional outcomes stay the same.


Key questions

Q: How should teams reduce AI coding agent costs without slowing delivery?

A: Start with the code paths agents touch most often. Smaller functions, clearer naming, and reduced nesting lower the amount of context the model must reconstruct, which cuts token burn and rework. Then measure input tokens, output tokens, and file revisits per task so you can prove whether refactoring is reducing runtime cost without harming delivery.

Q: Why does messy code increase the cost of AI-assisted development?

A: Messy code forces agents to read more, revisit earlier edits, and spend extra turns rebuilding context before they can safely change anything. That increases token consumption and review overhead even when the task still completes. The underlying problem is not model weakness alone. It is the friction created by low-legibility code structures.

Q: What are the signs that an AI coding agent is failing to understand a repository?

A: Look for duplicated logic, reintroduced anti-patterns, changes that ignore intended boundaries, and repeated reprompting after review. Those are strong indicators that the agent is optimising for plausible output instead of repository fit, which means context is missing or stale.

Q: Should engineering teams prioritize refactoring or prompt tuning first?

A: Refactoring should usually come first when the source code itself is hard to navigate. Prompt tuning can help at the margin, but the article shows that structural quality changes token use and reread behaviour directly. If the repository is tangled, better prompts will still have to compensate for a poor search surface.


Technical breakdown

Why agentic coding tools burn tokens on messy code

AI coding agents do not “see” code the way a human skim reads it. They repeatedly retrieve files, build context from prior turns, test a hypothesis, then re-send conversation history as they work. When methods are long, names are cryptic, and module seams are unclear, the agent must inspect more files and revisit earlier edits to stay oriented. That increases input tokens first, then output and reasoning overhead. The cost signal is therefore a function of navigability, not just size. The article’s core mechanism is that structural complexity forces broader context reconstruction on each turn, which compounds across a long task.

Practical implication: Treat code navigability as a cost control for AI-assisted development, not only as a maintainability metric.

Why cognitive complexity and naming matter more than comments

Cognitive complexity captures the branching and nesting that force any reader, human or machine, to trace multiple paths before making a safe edit. Clear identifiers and modular boundaries create direct lookup paths, while poor names and overgrown methods force search and reread behaviour. Comments help orientation, but the study’s ablation suggests they do not drive the token gap the way structure does. In other words, documentation can explain code, but it cannot fully replace code that is easier to target. The practical takeaway is that the cheapest agent interaction is one where the agent can locate the relevant branch or helper immediately.

Practical implication: Prioritise refactoring that shortens control flow and improves naming before spending time on more prose documentation.

Why clean boundaries reduce rereads in multi-module work

The strongest savings appeared where tasks crossed module boundaries. Clean interfaces let an agent cross from one component to another and keep its intent intact, while messy seams make it loop back to verify whether a change in one place broke assumptions elsewhere. That reread pattern is important because it shows where token spend originates in real work, especially in repositories where a task is distributed across several files. The study also shows a cautionary edge case: extraction that creates more files without making the target easier to find can increase effort rather than reduce it. Structure only helps when it improves discoverability.

Practical implication: Use boundary refactoring to make cross-module edits easier to target, and avoid decomposition that only spreads complexity around.


Threat narrative

Attacker objective: The objective in this pattern is not breach but inefficient consumption of AI compute, which can be exploited by poor code structure to inflate cost and effort.

  1. Entry begins when the coding agent is given a task in a repository whose internal structure is already difficult to navigate, so the first cost driver is context discovery rather than malicious execution.
  2. Credential-like abuse does not apply here, but the equivalent failure mode is repeated context harvesting, where the agent re-reads files and prior turns to recover lost orientation.
  3. Escalation occurs as the agent expands its search across more files, more branches and more conversation turns, increasing token use and operational cost without improving pass rate.
  4. Impact is higher AI spend and slower delivery, especially when the same repository is modified repeatedly and structural inefficiency compounds over time.

Read and download The State of NHI & AI Agent Breach Report 2026, covering 200+ breaches impacting Non-Human Identities including AI Agents.


NHI Mgmt Group analysis

Code structure is now an AI cost control, not just a maintainability concern. The Sonar study shows that the same repository can produce different agent footprints depending on how readable and navigable the code is. That means engineering governance has to treat structural quality as a budget variable, especially where AI coding agents are used at scale. The practitioner conclusion is that maintainability metrics belong in FinOps and delivery governance, not only in code review culture.

AI coding agents expose a hidden governance gap: organisations measure model spend more easily than code-driven spend. Teams often focus on model choice, prompt tuning or usage caps because those are visible controls, but the article shows that repository shape changes the bill materially. This creates a classic governance blind spot where the cost driver sits in the codebase, not the model platform. The practitioner conclusion is to govern the source material that agents consume, not only the agent itself.

Predictable names and clean seams are an access problem for agents as much as a productivity problem for developers. In NHIMG terms, the agent’s “access” is contextual access to code, and poor structure forces broader, noisier retrieval to achieve the same task. That makes code architecture a control surface for agent behaviour, especially when autonomous or semi-autonomous coding systems work across multiple repositories. The practitioner conclusion is that clearer structure reduces both operational drag and governance uncertainty around agent actions.

Structural debt and agentic drift can reinforce each other over time. The study’s per-task savings may look modest in isolation, but repeated agent work on the same repository can compound those savings or, if code quality degrades, compound the cost. That creates a named concept worth watching: agent navigation debt, where code becomes progressively more expensive for agents to traverse. The practitioner conclusion is to treat repetitive AI-assisted modification as a lifecycle governance issue, not a one-off productivity boost.

Cleaner code reduces the need for compensating controls in the AI layer. When a repository is easy to navigate, the agent spends less time searching, rereading and over-contextualising. That narrows the space in which teams must rely on prompt discipline or usage caps to manage cost. The practitioner conclusion is that structural remediation is often the stronger first control because it improves both the economics and the reliability of agent-assisted development.

From our research library:

What this signals

Agent navigation debt: when code becomes harder for AI coding agents to traverse, every subsequent task can cost more tokens, more rereads and more conversation turns. That turns maintainability into an operational control point for software delivery teams, especially where agentic coding is already in routine use.

The practical programme response is to optimise the code surfaces agents actually consume. Clean control flow, predictable naming and stable module seams reduce the need for compensating prompt discipline, and they make cost governance more measurable across repeated agent runs. according to the State of Secrets Sprawl 2026


For practitioners

  • Enforce cognitive complexity thresholds Add project-level thresholds for deeply nested methods and long switch statements so AI coding agents do not have to reconstruct control flow on every turn.
  • Refactor for discoverable names Replace opaque identifiers and helper names with predictable, search-friendly names that let agents target the right branch without scanning whole files.
  • Review module seams before agent rollout Map the files and interfaces an agent must cross for common tasks, then simplify seams that force repeated rereads or backtracking across boundaries.
  • Gate repeated agent edits with static analysis Run static analysis after each AI-assisted change so structural drift does not make the next task more expensive than the last.

Key takeaways

  • Cleaner code makes AI coding agents cheaper to run because the agent spends less time rebuilding context, rereading files and traversing unclear boundaries.
  • The Sonar study found lower token use and reasoning effort without a meaningful pass-rate penalty, which means the benefit is operational, not just theoretical.
  • Engineering teams should treat maintainability as part of AI cost governance, then use refactoring and static analysis to keep agent navigation efficient over time.

Key terms

  • Agent Navigation Debt: The accumulated cost created when AI agents must repeatedly search, reread and reconstruct context to complete routine work. It arises from poor naming, dense control flow and weak module boundaries, which make each task more expensive for the agent to traverse.
  • Cognitive Complexity: A metric that estimates how hard a function or code path is to understand, based on nesting, branching, and flow changes. Higher scores usually mean more mental effort for reviewers and a greater chance of maintenance errors.
  • Module Seam: The boundary where one part of a codebase hands work to another. Clear seams make edits easier to localise and verify, while tangled seams force agents to loop back across files and interfaces, increasing token use and operational friction.
  • Context Rehydration: The process of rebuilding enough prior state for an AI agent to continue a task after each turn. When a codebase is hard to navigate, rehydration consumes more tokens because the agent must carry and resend more history, more files and more surrounding logic.

Deepen your knowledge

The NHI Foundation Level course, the industry's only accredited NHI security programme, covers NHI governance, agentic AI identity and machine identity security in a way that supports security and engineering leaders. It helps practitioners connect identity governance to the broader delivery and operations controls their programme depends on.
NHIMG Editorial Note
Published by the NHIMG editorial team on August 18, 2026.
Updated on October 12, 2026.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org