By NHI Mgmt Group Editorial TeamDomain: AI SecuritySource: SonarPublished May 14, 2026

TL;DR: Cleaner code reduced agent cost and churn in a study of 540 Claude Code runs, with 7.2% fewer input tokens, 8.5% fewer output tokens, and 34% fewer file revisits, while task completion stayed essentially unchanged, according to Sonar. The finding reframes code quality as an AI infrastructure cost control, not just a developer experience issue.


At a glance

What this is: Sonar’s controlled study shows that cleaner code makes AI coding agents materially cheaper to run, but does not meaningfully change whether they complete the task.

Why it matters: For IAM and security teams, the result matters because AI-assisted engineering is becoming a governed runtime environment where structure, traceability, and access boundaries can influence cost, control, and reviewability.

By the numbers:

  • 540 runs, 40 runs, the cleaner side of each matched repository pair used 7.2% fewer input tokens and 8.5% fewer output tokens than the messier side.
  • The study measured 34% fewer file revisits after the agent had already edited a file on cleaner codebases.
  • Sonar reported 3.6% fewer turns before the first code change on cleaner repositories.

👉 Read Sonar's analysis of how cleaner code affects AI agent cost and reasoning


Context

AI coding agents do not just consume prompts, they consume code structure. When repositories are hard to navigate, with deep nesting, unclear names, and branchy control flow, the agent has to read more, revisit more, and reason longer before changing anything. That makes code quality an operational issue, not only a developer preference.

For identity and access teams, the relevant parallel is governance by legibility. Workflows that are difficult for humans to review are also harder for AI systems to process predictably, which matters as organisations expand agent-assisted development, code review, and remediation inside controlled software delivery pipelines.


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 signals show that an AI coding workflow is operating inefficiently?

A: Look for high token usage, repeated file revisits, and a long delay before the first meaningful edit. Those signals show the agent is spending runtime on context recovery rather than delivery. If those numbers fall after cleanup or refactoring, the workflow is becoming cheaper to run even if output quality stays steady.

Q: How do organisations decide whether code quality work is worth it for AI agents?

A: Compare refactoring effort with the amount of agent runtime it removes. If the same repositories are repeatedly driving extra reads, retries, and long edit cycles, structural cleanup can become a real operating-cost lever. The right decision framework is cost avoided per workflow, not code beauty in the abstract.


Technical breakdown

Why code structure changes agent behaviour

AI coding agents operate through repeated file reads, tool calls, edits, and retries. When a repository is cleanly factored, the agent can build a smaller working model of the task and reach an edit with less backtracking. When code is messy, the agent spends more time reconstructing context from nested logic, ambiguous naming, and spread-out dependencies. That does not necessarily stop the task from succeeding, but it changes the cost of getting there. The mechanism is not intelligence in the abstract. It is navigation friction, and that friction compounds across multi-step workflows.

Practical implication: teams should treat repository readability as a measurable control for agent efficiency, not just a style preference.

What token consumption actually measures in agentic workflows

In agentic development, tokens are not just prompt input and model output. They also represent the hidden work of reading files, revisiting earlier decisions, and iterating through tool interactions. That means code quality affects the entire inference path, not only the final generated patch. Clean code reduces the amount of context an agent needs to ingest before acting, which lowers both input and output token usage. This is why the study’s cost effect can exist even when pass rates barely move. The agent is getting to the same outcome through a cheaper path.

Practical implication: track agent token burn per task alongside outcome quality so you can see where structural cleanup reduces runtime cost.

Why AI infrastructure cost now includes code maintainability

The study reframes maintainability as part of AI operating cost. If a frontier-model agent can spend millions of tokens across one coding task, then every extra reread, retry, and context recovery step becomes a real budget factor. That shifts the economics of software engineering governance. Clean code is no longer only a developer productivity input, it is also a control on agentic inference spend. For organisations adopting AI-assisted engineering, the question is not whether agents can finish the work. It is how much compute and review overhead the codebase forces them to spend to do it.

Practical implication: add code-quality metrics to AI cost governance and use them to prioritise refactoring in high-volume agent workflows.


NHI Mgmt Group analysis

Cleaner code is becoming a governance control for agentic engineering. Sonar’s findings show that structural quality affects how much an AI agent must read, revisit, and re-reason before it acts. That turns code maintainability into an operational control surface, not merely a developer experience concern. For programmes adopting AI-assisted development, the governance question is now whether code structure is legible enough for both humans and machines to review safely.

Agentic inference creates a new cost model that security and engineering leaders will need to manage. Traditional software governance tracked build time, defect density, and delivery speed. Agent workflows add token consumption, file churn, and repeated context recovery to that picture. The named concept here is agentic inference drag: the extra runtime cost created when poor structure forces AI systems to spend tokens re-reading and reconstructing context. Practitioners should treat that drag as a budget and resilience issue, not an abstract model efficiency problem.

The study validates a broader identity-adjacent lesson: control depends on legibility. In identity programmes, access decisions fail when ownership, scope, and lifecycle are hard to trace. The same pattern now appears in AI-assisted coding, where the system can work harder but not necessarily better when the environment is opaque. That makes code quality part of the trust boundary around AI-enabled delivery, especially where agents can modify production-adjacent systems.

Task success alone is the wrong success metric for AI-enabled engineering. The study found little change in whether tasks completed, even while token consumption and rework fell on cleaner code. That means leaders should not use completion rate as the only measure of agent value. The more useful question is whether the programme is reducing cost, rework, and review burden while keeping the same delivery outcome.

What this signals

Agentic engineering is turning code structure into a security-adjacent operating variable. As AI systems take on more of the work of code reading and modification, organisations need to think about how reviewable, traceable, and bounded the codebase is before they let agents touch it. That is especially relevant where code paths include secrets handling, service credentials, or deployment automation.

The practical signal for programmes is simple: the teams that can show lower token burn, fewer rereads, and faster first-edit times will also have a better story for cost governance and change control. The better the code is organised, the easier it becomes to place human approval at the right control points and to detect when an agent is thrashing rather than delivering.


For practitioners

  • Measure agentic inference cost per task Track input tokens, output tokens, file revisits, and time to first edit for representative coding workflows so you can separate task success from runtime inefficiency.
  • Prioritise refactoring in high-volume agent paths Focus on repositories and modules where AI agents repeatedly touch the same files, since those paths are most likely to amplify token burn and reviewer churn.
  • Standardise code structure for machine readability Use smaller functions, clearer names, and predictable control flow in code that agents are likely to modify, because those traits reduce context recovery work.
  • Add AI cost signals to engineering governance Include agent runtime cost in engineering and GRC reporting so leaders can compare refactor effort with the token savings it unlocks over time.

Key takeaways

  • Cleaner code reduces AI agent runtime cost even when it does not materially change task completion rates.
  • Token burn, rereads, and first-edit latency are better indicators of agent efficiency than pass-rate alone.
  • For AI-assisted development, maintainability is now part of operating-cost governance, not only engineering hygiene.

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 surface, NIST AI RMF and NIST CSF 2.0 set the technical controls, and ISO/IEC 27001:2022 define the regulatory obligations.

FrameworkControl / ReferenceRelevance
OWASP Agentic AI Top 10The article concerns AI agents modifying code and re-reading context, which maps to agent misuse and workflow risk.
NIST AI RMFMANAGEThe topic is AI operational cost and risk management for coding agents.
NIST CSF 2.0PR.IP-1Repository structure and maintainability affect secure development process discipline.
ISO/IEC 27001:2022A.8.25Secure development principles apply where AI agents interact with source code.

Review agent workflows for context thrash, tool misuse, and excessive edit scope before expanding production access.


Key terms

  • Agentic Inference: Agentic inference is the multi-step work an AI agent performs while it reads files, calls tools, revisits context, and produces changes. In practice, it includes far more than prompt-and-response generation, which is why code structure can materially change cost and behaviour.
  • Token Burn: Token burn is the amount of model capacity consumed during a workflow, including inputs, outputs, and repeated context processing. It is a useful operating metric for AI programmes because it captures hidden runtime cost, not just whether a task eventually succeeds.
  • Code Legibility: Code legibility is the degree to which a codebase is easy to understand, navigate, and modify without excessive backtracking. For AI agents, legibility affects how much context they must reconstruct before making safe edits, which directly influences efficiency and review burden.
  • Agentic Inference Drag: Agentic inference drag is the extra cost and delay created when an AI system must repeatedly read, re-read, and reconstruct context before acting. It is a practical governance concept for measuring how poor structure turns into wasted runtime, tokens, and reviewer effort.

What's in the full report

Sonar's full research covers the experimental setup and run-by-run measurements this post intentionally leaves for the source:

  • Side-by-side repository design details showing how the clean and messy codebases were matched for architecture, dependencies, and test coverage
  • The 27-task experiment design, including how each task was routed through the codebase and why that routing matters for interpreting results
  • Per-task variance across the 540 runs, including where cleaner code helped most and where it slightly increased cost
  • Methodology notes on how reasoning effort was approximated from the event stream and why that matters for interpreting token economics

👉 Sonar's full research includes the matched-repo methodology, task design, and per-run measurements behind the findings

Deepen your knowledge

The NHI Foundation Level course, the industry's only accredited NHI security programme, covers NHI governance, machine identity security, and secrets management. It helps practitioners connect identity controls to the delivery systems and AI workflows that depend on them.
NHIMG Editorial Note
Published by the NHIMG editorial team on August 19, 2026.
NHI Mgmt Group — the independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org