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 study shows that code structure affects AI coding agent cost, with cleaner repositories reducing token use and reasoning effort without hurting task completion.
Why it matters: For IAM and security teams, the finding shows that structural quality decisions can shape the cost and control profile of agentic workflows, especially where AI tools touch code, secrets, and deployment paths.
By the numbers:
- Agents working on cleaner code used 7.1% fewer input tokens in Sonar’s controlled study.
- Teams mixing inline completion and agentic coding tools now spend $200 to $600 per engineer per month, according to DX research.
- The FinOps Foundation says AI spend moved from 31% of teams actively managing it two years ago to 98% today.
👉 Read Sonar’s analysis of how code cleanliness affects AI coding agent cost
Context
AI coding agent cost is not only a model or prompt problem. When repositories are structurally hard to navigate, agents spend more tokens reading, re-reading, and verifying the same logic, which pushes up runtime cost and creates governance pressure around where AI assistance is actually efficient. This matters in primary keyword terms because AI coding agent spend is now tied to code quality, not just usage policy.
Sonar’s study is useful because it separates the cost drivers that teams usually conflate. The work suggests that cleaner module boundaries, clearer names, and lower cognitive complexity reduce the amount of work an agent has to do to understand a repository. For identity and security teams, that has a direct intersection with secrets exposure, code review discipline, and the controls surrounding AI-assisted development pipelines.
The practical starting point is typical rather than exceptional: many engineering organisations already have code quality tooling, but few treat maintainability as an AI cost control. The article shows that this blind spot is now measurable, not theoretical.
Key questions
Q: How should security teams manage AI coding agents in repositories with poor code structure?
A: Start by reducing the amount of code an agent must inspect to complete a task. Dense control flow, unclear names, and tangled module boundaries force repeated reads, which increases cost and broadens context exposure. Improve structure first in repositories that contain secrets, deployment logic, or privileged automation, then measure whether token use and rereads fall.
Q: Why does code structure affect AI coding agent costs so much?
A: Agentic tools do not just generate text. They read, plan, edit, verify, and often re-read the same files as context changes, so every extra branch or seam adds work. Cleaner repositories give the model a narrower path to the answer, which lowers token consumption and reasoning effort without changing the application itself.
Q: What do teams get wrong about using comments to help coding agents?
A: Comments can help, but they do not fix a hard-to-navigate structure. If the code remains densely branched or poorly named, the agent still has to read broadly and verify its path. Structural clarity usually matters more than documentation volume, especially in multi-module work.
Q: How do I know if code quality controls are reducing AI spend?
A: Track token usage, reread frequency, and conversation turns before and after structural changes. If the repository is easier for the agent to navigate, those numbers should fall while pass rates stay stable. That gives you evidence that refactoring is reducing runtime cost, not just improving aesthetics.
Technical breakdown
Why cognitive complexity changes agent runtime cost
Cognitive complexity measures how hard code is to understand because of nested branches, loops, and control flow, not how many lines it contains. Agentic coding systems pay for that complexity by consuming more context, revisiting files, and re-evaluating execution paths before they edit. Sonar’s finding is important because the cost is architectural: a dense method forces broader reading, while a well-factored function lets the agent target a smaller slice of context. That is why structural quality can lower both token usage and reasoning effort even when functionality is unchanged.
Practical implication: treat cognitive complexity thresholds as a cost control for AI-assisted development, not only as a maintainability metric.
Why names and module seams matter for AI coding agents
Predictable names and clean interfaces reduce search work. If an agent can infer where a function lives from a stable name or follow a boundary without re-checking downstream code, it spends fewer tokens locating the right edit path. Sonar’s results on multi-module tasks show that this effect becomes stronger when work spans several components, because clear seams prevent the agent from looping back across the same files. By contrast, extraction that creates more files without improving findability can increase the surface area the agent must inspect.
Practical implication: prioritise naming consistency and navigable module boundaries before adding more helper extraction.
Why structural quality is now a FinOps issue
Agent usage cost compounds because the model reprocesses the conversation and repository context on every turn. That means code structure affects not just developer experience but the size of the bill generated by repeated agent runs. Sonar’s work sits alongside other research showing that agentic coding tasks consume far more tokens than single-turn chat, so the biggest hidden cost is often the codebase itself. In identity-sensitive environments, that matters where agents touch credentials, deployment files, or security logic and must re-read surrounding context before acting.
Practical implication: include code quality and repository structure in AI cost reviews, especially for pipelines that handle secrets or privileged automation.
NHI Mgmt Group analysis
Code quality is now part of AI governance, not just software hygiene. Sonar’s study shows that structural defects increase the cost of agentic coding without improving completion rates, which means maintainability is becoming a control objective. In practice, teams that ignore code structure are also accepting higher AI runtime spend and more review friction. The governance conclusion is straightforward: AI-assisted development needs structural quality thresholds, not just usage caps.
Maintainability debt is becoming agentic AI cost debt. The article makes clear that token consumption rises when agents must compensate for poor naming, tangled control flow, and weak module boundaries. That creates a new kind of operational debt where technical structure directly drives operating cost. For practitioners, the lesson is that refactoring is now a financial and governance decision, not only an engineering preference.
Identity-adjacent workflows inherit the same structural risk, especially where code touches secrets and access paths. When agents work inside repositories that contain deployment logic, credential handling, or security policy code, poor structure increases the chance of repeated reads and broad context exposure. That does not make every codebase an identity problem, but it does make NHI governance relevant wherever agentic tools can reach secrets or privileged automation. The control question is whether those paths are clean enough to limit unnecessary exposure.
Cognitive complexity density: this is the practical concept the article sharpens, because it describes how tightly packed control flow translates into higher agent navigation cost. Sonar’s data suggests that density, not size alone, is what drives repeated rereads and token churn. Teams should therefore track structural density at the repository and module level, then use it to prioritise refactoring where agent usage is heaviest.
Code structure is becoming a shared concern between engineering, FinOps, and security. Sonar’s findings align productivity, cost, and governance around the same structural controls. That convergence matters because AI tooling is now part of the production stack, not a side experiment. Practitioners should expect code quality reviews, cost reviews, and security reviews to converge around the same repositories.
What this signals
Cleaner code is becoming a measurable control for AI-assisted development, which means security leaders should expect code quality, cost, and governance reviews to converge around the same repositories. The practical signal is that teams with heavy agent use should monitor not only spend but also rereads, turn counts, and structural density because those are the variables most likely to move first.
Maintainability debt: this is the emerging operational risk where code structure directly inflates AI runtime cost. Teams that already manage secrets, deployment logic, or access paths in code should treat repository cleanliness as part of the control environment, not as a separate engineering concern.
For identity and NHI programmes, the signal is narrower but important: whenever AI agents can reach privileged code, deployment pipelines, or secret-bearing configuration, poor structure increases the amount of surrounding context they must inspect. That makes repository hygiene relevant to exposure management as well as developer productivity.
For practitioners
- Apply cognitive complexity thresholds to agent-heavy repositories Set explicit thresholds for methods and modules that are frequently touched by coding agents, then refactor the highest-density paths first. Use those thresholds as part of merge gating so the same structural issues do not keep inflating token use.
- Prioritise naming and boundary cleanup before broad refactoring Target the functions, files, and interfaces that agents repeatedly search for, especially in multi-module workflows. Clear names and stable seams reduce rereads more effectively than adding more helper layers or extra comments.
- Treat AI coding cost as part of FinOps reviews Include token spend, session length, and reread frequency in your cost management process, especially for teams that use agentic tools daily. Compare those costs before and after structural remediation to prove whether the refactor paid back.
- Protect secrets and privileged paths from unnecessary agent context Review repositories that contain credentials, deployment automation, or access-control logic to ensure agents do not need broad context to make simple changes. Clean structure reduces how much sensitive surrounding code the agent must inspect.
Key takeaways
- Sonar’s study shows that code structure changes the cost of AI coding agents even when task success stays flat.
- The evidence points to a governance shift where maintainability, FinOps, and security now share the same structural controls.
- Teams should measure agent token use, rereads, and cognitive complexity together, then refactor the repositories that drive the highest cost.
Standards & Framework Alignment
This section maps relevant standards and security frameworks to the operational risks and controls described in this guidance.
OWASP Agentic AI Top 10 address the attack and risk surface, while NIST AI RMF, NIST CSF 2.0 and CIS Controls v8 set the governance and control requirements practitioners need to meet.
| Framework | Control / Reference | Relevance |
|---|---|---|
| NIST AI RMF | GOVERN | AI-assisted coding cost and governance are central to the article. |
| OWASP Agentic AI Top 10 | Agentic coding workflows inherit prompt, context, and tool-use risks. | |
| NIST CSF 2.0 | PR.DS-5 | Repository structure and secrets-bearing code affect data protection outcomes. |
| CIS Controls v8 | CIS-16 , Application Software Security | Code quality and secure software practices shape the control environment here. |
Apply data protection controls to repositories that expose secrets, deployment logic, or security policy code.
Key terms
- 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.
- Agentic coding assistant: An AI-assisted development tool that can decompose tasks, choose actions, and execute parts of a workflow inside the editor. In security terms, it behaves like a non-human identity when it can access code, tools, and terminals on behalf of a developer, so governance must cover its runtime behaviour.
- Module Boundary: The seam between components or files that separates responsibility and limits how much surrounding code must be understood at once. Clean boundaries reduce search and reread work for both humans and AI agents, while tangled boundaries increase runtime cost and review friction.
What's in the full report
Sonar's full analysis covers the experimental design and task-level measurements this post intentionally leaves for the source:
- Matched repository-pair methodology showing how clean and degraded codebases were built and compared
- Task-by-task token and reasoning deltas across 660 Claude Code trials, including variance by repository pair
- The comments normalisation ablation and why structure, not documentation volume, drove the footprint difference
- The long-horizon hypothesis comparing per-task savings with structural drift over repeated agent edits
Deepen your knowledge
The NHI Foundation Level course, the industry's only accredited NHI security programme, covers NHI governance, agentic AI identity, machine identity security, IAM, and secrets management. It helps security practitioners connect identity control choices to the broader security programme they run.
Published by the NHIMG editorial team on August 18, 2026.
NHI Mgmt Group — the independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org