AI Coding Agents in a Large Codebase: Fix the Code, Not the Agent
AI coding agents get lost in big repos and guess on domain code. Measure per module, refactor to common idioms, then map, fence and verify each module.
Key takeaways
- Agents write code well to the degree it looks like their training data, so domain modules like Z-segment parsers or Mirth channel scripts are the likely weak spots.
- Measure first-pass acceptance per module, not repo-wide, and take the baseline before changing anything so you can tell which change moved which module.
- Refactor generic code to common idioms, keep short owned CLAUDE.md files per module, fence imports in CI, and require fixture replay before an agent calls domain work done.
AI coding agents struggle in large codebases for two separate reasons. There's too much code to find the right file by grepping and following imports. And the code that matters most often looks nothing like what the model was trained on. Better prompts won't fix either one. The fix belongs in the codebase, one module at a time.
The agent is a neural network with priors from its training data. That's the Software 2.0 idea applied to the tool itself. It writes your code well to the degree that your code looks like code it has seen. Where yours doesn't, it produces the familiar shape without flagging the difference.
At MedScrub, the hardest problem was filtering noise out of messy charts and surfacing only what's useful. The code that decides what counts as noise is product logic. No model has seen it. Auth, API routes and job queues it has seen many times. Plan around that split: lean on the agent for the second kind, and build guardrails around the first.
I don't have before-and-after numbers from my own repos yet. What follows is the method, and Step 1 is how you find out whether the premise holds on yours.
What out of distribution looks like in healthcare code
Healthcare integration code is full of it. HL7v2 Z-segments are site-defined and often vary between feeds. CDS Hooks services have to absorb EHR-specific behavior. FHIR profiles often get extended locally. Each of these looks close to something common, and that's the dangerous case.
A Mirth channel script is the clearest example. It looks like JavaScript, so an agent writes it like Node. It isn't Node. It runs in Mirth's embedded Rhino engine. There's no require and no npm. The inbound HL7v2 message is msg, an E4X XML object, not a parsed JSON tree.
That difference breaks the most ordinary guard. Read a field the message doesn't have and you don't get undefined. You get an empty XMLList, and an empty XMLList is an object, so it's truthy. The Node-shaped check if (msg['ZPI']['ZPI.3']) passes on every message, including the ones without the field. The Mirth-shaped check is msg['ZPI']['ZPI.3'].toString() != ''. Same trap with counts: in E4X, length() is a method, so .length without parentheses gives you a function, not a number. Values a later connector needs go in channelMap.put(...), not a variable.
None of that code looks wrong. It reads like competent JavaScript. It just isn't the JavaScript this runtime executes.
Why AI coding agents fail in large codebases
Sourcegraph ran 1,281 scored agent runs across 40+ large open source repos. Agents limited to grep, file read and glob "begin to struggle systematically" above roughly 400,000 lines. Sourcegraph itself says that figure isn't a universal cutoff: size, task type, language and harness all move it. The most common failure was getting lost: read a file, follow its imports, read the next file, until the search tree branches faster than the agent can prune it. On a Kubernetes task across 1.4M lines of Go, the local-tools agent ran for 6,000 seconds and produced nothing. The same model with indexed search and find-references finished in 89 seconds and scored 0.90.
Sourcegraph sells code search, so read the framing with that in mind. They call these "context problems, not intelligence problems." For navigation, I agree. But the benchmark runs on large open source repos, which may well overlap with training data, so it can't isolate the second problem. A smarter model with perfect search still doesn't know what your site's Z-segment means, or that an empty XMLList is truthy. No index fixes that.
Agent tooling matters, and I've covered what the teams actually shipping coding agents have figured out. This post is about the other half: the codebase.
Step 1: Measure whether coding agents work on your codebase, per module
Tag every agent-authored PR with a label or a branch prefix. For each one, record which modules it touched, whether it merged with no human-requested changes, and whether a human reworked those lines within two weeks. A PR that clears both checks counts as a first-pass acceptance.
Report that rate per module, not across the repo. A repo-wide average hides the few directories where agents fail. Sort by module. The bottom of that list is your out-of-distribution map. If your domain modules don't sit at the bottom, my premise is wrong for your repo, and you should spend your effort on tooling instead.
Take the number now, before you change anything. Every step below should move it for a specific module. If a step doesn't move it, undo the step.
Step 2: Refactor generic code to patterns the model already knows
Treat novelty as a budget. Every custom abstraction in generic code is something the agent has to learn from your repo instead of from its priors. A homegrown dependency injector, a clever result type and a bespoke HTTP wrapper all cost something. Replace them with the most common idiom in your stack. Boring code is code the model already knows.
Spend novelty only where the domain requires it. Don't converge shapes that carry meaning. Z-segment handling usually depends on field position and site conventions. Normalizing it into a generic key-value map can make it look familiar and lose what the positions mean. Same for Mirth: you can't refactor a channel script into Node, because the runtime won't run it. My rule: if a domain expert would object to the rewrite, leave the code alone and map it instead.
Step 3: Write a CLAUDE.md file for each module
Claude Code loads CLAUDE.md from the working directory and every directory above it. It also discovers CLAUDE.md files in subdirectories, so a per-module file sits right where the agent works. This is context engineering at module scope. Each file holds four things: the invariants, one canonical example to copy, the places the agent must not touch, and what done means. Here's the shape, for an illustrative Z-segment module:
# hl7/zsegments
Owner: @integration-team
Reviewed: 2026-05-01
## Invariants
- Z-segment fields are positional. Never reorder or rename them.
- Unknown Z-segments pass through untouched. Never drop them.
## Copy this
- parsers/zpi.ts is the canonical parser. New segments follow its shape.
## Do not touch
- encoding.ts (delimiters and escape handling)
- vendor/
## Done means
- npm run replay:hl7 passes with zero unexplained diffs.
For a Mirth channel directory, the invariants are the runtime facts from above: no require, check fields with .toString() != '', pass values between connectors through channelMap.
Keep it short. Every line competes for attention, and a bloated memory file is its own form of context rot. One example beats five paragraphs of description.
The file needs an owner, because the agent trusts it and a stale map is worse than no map. CI flags any module file that is older than the code beside it:
#!/usr/bin/env bash
# Flag module CLAUDE.md files older than the code beside them.
# '*/' skips the root CLAUDE.md. CI needs full history: fetch-depth: 0.
for f in $(git ls-files '*/CLAUDE.md'); do
dir=$(dirname "$f")
doc=$(git log -1 --format=%ct -- "$f")
code=$(git log -1 --format=%ct -- "$dir" ":(exclude)$f")
if [ "${code:-0}" -gt "${doc:-0}" ]; then
echo "stale: $f ($(grep -m1 '^Owner:' "$f"))"
stale=1
fi
done
exit ${stale:-0}
The check fires on any change in the directory. To clear it, the owner reads the file, fixes anything that's wrong and commits it, even if the only change is a new Reviewed: date. The root CLAUDE.md is skipped because it would fire on every commit in the repo.
Step 4: Fence module boundaries and give the agent LSP across them
Code outside a module shouldn't reach past its public entry point. Put typed interfaces at module boundaries and enforce import rules in CI:
// .dependency-cruiser.js
module.exports = {
forbidden: [
{
name: "hl7-public-api-only",
severity: "error",
from: { path: "^src/(?!hl7/)" },
to: { path: "^src/hl7/(?!index\\.ts$)" },
},
],
};
In one Sourcegraph example, a baseline agent changed 2 of 7 affected files in a cross-file refactor. That left the API contract at the changed site out of step with the call sites it never touched. In a typed language, the type check catches that. The import fence makes sure every caller goes through the one typed entry point, so no stale caller sits outside it. With both in place, a mismatch like that is far more likely to fail the build than to ship.
Fences also make parallel work safer. If each agent owns one module and can only cross into others through typed entry points, two agents can't quietly edit the same internals. That's the same worker isolation I lean on in multi-agent orchestration, applied to the repo instead of the runtime.
For navigation across boundaries, give the agent go-to-definition and find-references through LSP or a call graph. In Why I Stopped Using RAG for Coding Agents, I argued for letting the agent explore code the way a senior engineer would: read files, follow imports. Inside a module, that still holds. Across a big repo, following imports by hand is the strategy that gets lost. The data matches. Below Sourcegraph's threshold, code intelligence tools slightly hurt results (-0.080). Between 400K and 2M lines they helped most (+0.259). Use grep inside a module and structure across modules.
Step 5: Verify per module before the agent says done
"Tests pass" means something different in each module. For generic code it means lint, typecheck and the unit suite. For domain-heavy modules that isn't enough, because the agent's tests can come from the same wrong priors as its code. An agent that thinks if (msg['ZPI']['ZPI.3']) works will write a test with the field present, and the test will pass.
So domain-heavy modules require fixture replay. Capture real messages and payloads, de-identify them, replay them through the module and diff the output against known-good. Include messages that are missing the optional fields. The agent can't call the work done until the diff is clean or every changed line is explained in the PR. The full loop for interface code is in Claude Code for FHIR and HL7v2: validator, replay diffs, terminology checks, PHI hooks.
Put the requirement in the file's "Done means" line and enforce it in CI. In these modules, the agent's own opinion that it's done counts for nothing.
Expect replay to lower first-pass acceptance at first. The agent now has to put every unexplained diff in the PR, and reviewers request changes on things they used to miss. Problems that once surfaced weeks later as rework, or never surfaced at all, now show up in review. That drop means the gate is working, not that the agent got worse.
How to tell if it's working
If a CLAUDE.md file doesn't move its module's number within a few weeks of agent PRs, rewrite it or delete it. If a fence never fires, it's guarding the wrong seam. If none of it moves anything, your problem is navigation, not distribution, and the tooling fix is the right one.
I'll publish my own per-module numbers once I have them. Until then, don't take this on faith. Take the baseline, change one module, and look.
Questions people ask
Why do AI coding agents struggle in large codebases?
There's too much code to explore by grepping and following imports, and in Sourcegraph's benchmark the most common failure was the agent getting lost. Domain-specific modules may also not look like the model's training data, so even good search doesn't tell the agent what that code means.
Should I give my coding agent LSP or code search instead of grep?
Use grep inside a module and structural navigation like find-references across modules. Sourcegraph found code intelligence tools slightly hurt results below roughly 400K lines (-0.080) and helped most between 400K and 2M lines (+0.259), and it says 400K isn't a universal cutoff.
What should go in a per-module CLAUDE.md file?
The module's invariants, one canonical example to copy, the places the agent must not touch, and what done means. Keep it short, give it an owner, and have CI flag it when it's older than the code beside it.
How do I measure whether a coding agent works on my codebase?
Tag agent-authored PRs and track first-pass acceptance per module: merged with no human-requested changes and no human rework within two weeks. Sort by module, because a repo-wide average hides the few directories where agents fail.