Skip to content
BACK TO ARTICLES

Should You Write Code for AI Agents or Human Readers?

Use one style guide for humans and AI coding agents. Diagnose navigation costs, missing explanations, and skipped prerequisites before refactoring.

Dosu
/
Oct 29, 2026/10 min read

Write code for the people who maintain it, and use the same style guide when AI coding agents contribute. Keep descriptive names, useful comments, appropriate types, and meaningful tests. Change function boundaries or module structure for agents when session evidence identifies a navigation problem worth fixing.

The studies cited here measure agent costs and recurring discoveries. They do not compare code styles. The recommendations below explain plausible trade-offs and give you a way to investigate them without committing to a codebase-wide rewrite.

Why can code navigation cost more for an agent?

An agent without relevant project context may need to inspect implementations that an experienced maintainer recognizes. A new engineer faces a similar problem. The difference depends on the context each reader brings to the task.

An agent can gather context through searches, file reads, instructions, and saved knowledge. When a task requires tracing several implementations, those reads can add tool calls and input tokens. A function call does not necessarily require a separate search, and a fresh task does not necessarily start without useful project knowledge.

In Dosu's replay of 112 agent sessions on the public cal.diy repository, Claude Code's average modeled cost was $1.11 for self-contained tasks and $4.96 for cross-cutting tasks, about 4.5 times higher. The sessions replayed selected pull-request tasks on earlier repository states. Costs used standard API rates, and the study did not score correctness or test style changes. The result gives a reason to investigate the context a task requires, but it does not establish that flattening call chains will make agents cheaper.

Which clean code practices should you keep for AI agents?

Keep practices that make responsibilities, contracts, and expected behavior explicit. Naming, comments, types, and tests give both maintainers and agents information they can use without reconstructing every design decision.

Do descriptive names help agents find relevant code?

Use names that identify a symbol's responsibility. A search result containing loadAccountPermissions gives a reader more information about its purpose than getData. An agent may also see the path and nearby code, so the name is one signal rather than its only context. Keep naming standards consistent, and investigate actual discovery failures before starting a renaming project.

Where should comments and docstrings explain behavior?

Keep explanations of local behavior beside the code they describe. A comment explaining why a request retries after a particular error is useful when a human or agent opens that retry logic. Put rules that span modules in a shared instruction or documentation location, with a local reference where needed. A comment cannot help a session that never reads the relevant code.

Do type annotations replace implementation reads?

Type annotations expose part of a contract, but they do not necessarily explain side effects, invariants, or runtime behavior. Follow the project's typing policy and make its type checker available during agent work. A checker can turn some incorrect assumptions into actionable errors. The cited studies do not measure whether adding annotations improves agent performance.

What do tests tell an AI coding agent?

Tests and type checkers both provide executable feedback. Tests check specific assertions about behavior, while type checking checks contracts expressed in the type system. Passing checks means those checks passed under the tested conditions.

An agent changing authorization logic can pass happy-path tests while introducing an access-control bug. Include denied requests and boundary cases among the behaviors the change must preserve. Judge the change by whether the checks cover those risks. A green suite alone does not show that the change is safe.

Are short functions still useful for AI coding agents?

Keep short functions when they express a coherent operation. Do not inline functions solely to reduce agent navigation. Investigate deep call chains when session logs show repeated reads across implementation boundaries.

Function length and call-chain depth are different properties. A short function can expose a useful contract, while a chain of small wrappers can require several implementation reads to understand one operation. Keep a sequence together when its steps form one task, and extract a function when the extraction names a useful responsibility.

The studies cited here do not measure a cost per call-chain hop. Before removing a layer, identify which information the agent needed and whether a clearer interface or contract would supply it.

Should you duplicate code to reduce agent navigation?

Do not duplicate a shared business rule solely to save file reads. Ask whether the implementations represent the same rule and must change together. Shared logic can prevent a fix from reaching one copy while leaving another unchanged.

Similar code may be appropriate when two modules own independently evolving behavior. When an agent introduces duplication, check whether it found and evaluated the existing implementation. When an agent misses a helper, fix discovery and keep the team's DRY ("don't repeat yourself") rule in place.

When do abstraction layers help AI agents?

Keep abstractions that let a reader work from a useful contract. If callers routinely need details that the interface does not explain, improve the contract or reconsider the boundary.

For example, an agent investigating retries may need to know which errors trigger another attempt and when attempts stop. If a wrapper hides those rules, documenting the contract may be enough. Opening its implementation does not prove the wrapper has no value. Preserve useful responsibilities when simplifying a layer.

Do smaller files help AI coding agents?

Do not split files solely to meet an agent-specific line limit. Organize modules around cohesive responsibilities, then inspect how the agent retrieves the code needed for its task.

An agent with span-based retrieval can inspect part of a long file. Another tool or task may lead it to read the whole file. Splitting related behavior across several modules can also increase navigation. File length alone does not establish which arrangement costs less or produces a better change.

For repository setup and verification guidance beyond code style, see What Makes a Codebase Easy for AI Coding Agents to Work In.

When should you update instructions instead of refactoring?

Update instructions when a session lacks a useful explanation. Improve discovery when the explanation or helper exists but the agent does not find it. Automate a prerequisite where possible when the agent reads the requirement but skips it.

In Dosu's analysis of 107 agent sessions on Vercel's AI SDK, model-extracted findings identified the same build requirement in 59 sessions across 40 tickets. In one inspected replay, tests could not import @ai-sdk/provider-utils because the workspace package's compiled output was missing.

Codex loaded AGENTS.md in every included run. At the revision checked, that file listed pnpm install followed by pnpm build, but did not connect the failed import to the missing build. The underlying package exports and build configuration supplied evidence for the diagnosis. The missing piece was a note that connected the prerequisite to the import failure where the agent hit it.

Setup automation can enforce the build before tests. A troubleshooting note can explain the symptom, cause, and recovery command when a direct test invocation bypasses that workflow. The study used fresh checkouts on selected tickets and did not verify a failure-and-fix sequence in every counted session. The counts describe extracted findings, not the frequency of this failure in everyday development.

Use the observed problem to choose a first response:

Observed problemFirst responseWhat to verify
The agent repeatedly traces implementations for a small change.Inspect the interfaces and navigation paths involved.A clearer contract or simpler path reduces unnecessary investigation without losing correctness.
The agent misses an existing helper.Improve discovery and check how it searched for reusable code.A later session finds and evaluates the helper.
The agent reconstructs an undocumented explanation.Record the symptom or question, explanation, and supporting source.A later session retrieves an accurate explanation that applies to its task.
The agent reads a prerequisite but skips it.Enforce the prerequisite in the workflow where possible.The required step runs before the dependent operation.
The sampled sessions show no clear recurring problem.Gather more evidence before changing the style guide.The proposed change addresses an observed problem.

How do you inspect agent sessions before refactoring?

Inspect several comparable sessions, identify a recurring problem, and test one targeted change. A transcript review can reveal a candidate improvement. It does not establish that a refactor will reduce cost or improve correctness.

Decant is the open source tool Dosu used for the studies above. It indexes local agent logs and provides a transcript viewer and cost analytics.

  1. Start Decant and let it index your sessions.

    npx @dosu/decant@latest
    
  2. Stop the local UI with Ctrl-C after indexing. Get an archive-wide token, cost, and time breakdown.

    npx @dosu/decant@latest economics
    

    The economics report covers the indexed archive without repository, task, or date filters. It does not calculate the cost share before the first edit.

  3. List sessions, then open one. Replace the example session number 1 with the number shown in your list.

    npx @dosu/decant@latest ls
    npx @dosu/decant@latest show 1
    
  4. Locate the first code-changing action. Inspect the searches, reads, and failures before it, then check whether the same problem recurs later in the session. Record what information the agent needed and what finally supplied it.

Reading a transcript shows what the agent investigated. Calculating a dollar share requires token accounting and pricing as well. In the cal.diy replay, 46% of modeled cost occurred before the first edit, but early investigation also includes necessary work. The percentage is not a target to minimize on its own.

After one targeted change, compare similar tasks using the same tool and model configuration where practical. Assess total cost, completion time, and correctness alongside files read. Fewer reads help only if the agent still obtains the context needed to make a correct change.

FAQ

Should we keep a separate style guide for agents?

Use one style guide by default. A separate guide adds maintenance and creates another place for rules to diverge. If an agent misses a convention, check whether it loaded the instruction, whether the instruction was clear, and whether an automated check can enforce it.

Should style rules live in the linter or the instruction file?

Encode style rules in automated checks whenever those checks can express them. Make the checks available during the agent's workflow, with CI as a backstop. Keep explanations and exceptions in instructions or documentation, such as why a deprecated API must remain available until a customer migrates.

Do these recommendations apply to Cursor, Codex, Copilot, and Claude Code?

Use the recommendations as a starting point, then inspect sessions from the tool your team runs. Retrieval behavior, instruction loading, and retained context differ across tools and configurations. A finding about one tool's navigation does not establish the same cost or behavior for another.

Should you optimize code for what a model can generate easily?

Prioritize maintainable code and verifiable behavior. The studies cited here do not evaluate which code patterns models generate most reliably. Any proposed model-specific convention should demonstrate a useful improvement on your tasks without imposing an unacceptable maintenance cost.

Give the next agent an explanation it can check

Choose one recurring question from a recent session. If the answer belongs in reusable project knowledge, record the symptom or question, the explanation, and the supporting source. Check that the next session can retrieve it and that the advice still applies.

Create a Library and connect that repository. Dosu can study your existing Claude Code, Codex, and Cursor sessions and save findings such as build requirements and code locations to your Library. Your team and connected coding agents can retrieve those findings on later tasks. Review the saved explanation and its sources before relying on it.

Ready to transform your workflow?

Join leading organizations using Dosu to automate documentation, streamline support, and empower development teams to focus on building great products.