Million+ LOC strategies for coding agents
PLMillion+ LOC strategies for coding agents rely on disciplined context selection rather than brute context capacity. Layered instruction files encode architecture, a code-intelligence MCP server resolves symbols and cross-package callers, a read-only blast-radius report inventories every affected consumer before edits start, and deterministic CI gates prove large changes without line-by-line reading.
Developers making changes in massive repositories and tech leads designing shared harness standards face the same failure mode. You inherit a 1.8-million-line monolith whose original architects left two years ago, and your first ticket renames User.role. An agent updates three files in packages/web, reports green unit tests, and two hours after deploy billing-worker crashes because it reads the same field from a shared event payload the agent never loaded. The failure happens during discovery: the crucial caller stayed invisible.
Why larger context windows fail at million-line scale
Section titled “Why larger context windows fail at million-line scale”No context window holds a multi-million-line codebase cleanly, and stuffing a large fraction of the window with tangential files degrades reasoning long before token limits hit (see context windows). At scale, you engineer what loads in three layers so every token earns its seat:
| Layer | What it carries | Where it lives | Loading rule |
|---|---|---|---|
| Architecture | Module map, dependency direction, cross-service schema rules, single-command checks | Root AGENTS.md, CLAUDE.md, or always-apply Cursor rule | Every session (keep compact, ≤ 150 lines) |
| Domain | Package invariants, money/auth rules, local test commands | Nested AGENTS.md, .claude/rules/, or glob-scoped .cursor/rules/*.mdc | Only when touching that package |
| Implementation | Target files, direct callers, and one reference pattern to imitate | Retrieved via symbol navigation or targeted search | On demand, per task |
Write the architecture layer once and prune it regularly; every unnecessary line taxes every session across the team. See AGENTS.md context design and pruning context files for how to keep root instructions lean.
How each tool loads layered instructions
Section titled “How each tool loads layered instructions”Nested rules prevent domain invariants from polluting unrelated sessions, and each tool evaluates them differently:
- Claude Code: Loads
CLAUDE.mdupward from the working directory at launch and loads subdirectoryCLAUDE.mdfiles on demand when reading inside them. Use path-scoped rules in.claude/rules/for file patterns that cross directories, and delegate shared rules via@AGENTS.mdto avoid drift. Check the Claude Code docs for current precedence rules. - OpenAI Codex: Automatically loads
AGENTS.mdfrom the repository root down to the directory where you launch the session, capped by its project document byte budget. Long root files crowd out package files. Start sessions inside the target package when its invariants are mandatory, or point explicitly to the package brief in the task specification. See the Codex docs for current hierarchy and sandbox configuration. - Cursor: Encodes the architecture layer in
.cursor/rules/*.mdcwithalwaysApply: true(or rootAGENTS.md) and domain invariants withglobsordescriptiontriggers. Commit.cursorignoreto exclude generated clients, lockfiles, and snapshots so boilerplate never swamps workspace search. See the Cursor docs for rule frontmatter and ignore syntax.
Replace grep loops with code intelligence
Section titled “Replace grep loops with code intelligence”Exploring a million-line codebase via repeated text searches burns context on false positives and misses dynamic or re-exported references. Connecting a code-intelligence server over the Model Context Protocol lets agents resolve definitions, references, and call paths in a single structured query. Choose the indexing strategy that matches your security posture and query type:
| Strategy | Best for | Trade-off |
|---|---|---|
| Language Server (LSP) MCP (e.g., Serena) | Exact symbol resolution, cross-package renames, finding typed callers | Stays strictly local; requires healthy language servers per stack |
| Tree-sitter / call-graph MCP | Fast structural graphs and call-path tracing across polyglot repos | Stays local; misses runtime reflection and untyped event payloads |
| Hybrid vector + BM25 search MCP | Conceptual questions (“where do we retry failed charges?”) when naming is inconsistent | Requires an index pipeline; evaluate data residency before sending code chunks to hosted embedding APIs |
Register heavy MCP servers at project scope only where repositories truly need them: every registered server injects tool definitions into every turn. Compare architectural trade-offs in the MCP hub.
Order of operations: map, blast radius, contract-first slices
Section titled “Order of operations: map, blast radius, contract-first slices”In large repositories, order of operations determines whether errors surface in seconds via the compiler or hours later in production.
- Maintain a persistent architecture map. Commit a concise
docs/architecture/map.md(under 300 lines) listing top-level packages, owned tables, dependency direction, and every untyped cross-service consumer (events, queues, shared tables, config keys). Regenerate and diff it after major merges. - Generate a read-only blast-radius report. Before cross-package edits, inspect code, event schemas, SQL migrations, serializers, fixtures, and feature flags to emit a
FILESlist and rank the five riskiest files. If a known consumer is missing, stop and fix indexes or ignore rules first. - Mutate shared contracts first. Commit
blast-radius.txton the feature branch, then update shared types, schemas, and migrations in slice 1 so compiler errors produce an independent consumer list. - Execute one package per isolated slice. Bound each slice to one reviewable PR. Fan independent package updates across isolated worktrees or cloud runs—sized strictly to review capacity (git worktrees, orchestration patterns).
- Reset context between tasks. Start fresh or compact explicitly whenever switching slices or repeating a correction twice.
How to verify a 60-file change without reading every line
Section titled “How to verify a 60-file change without reading every line”You approve a cross-package change because independent, falsifiable gates pass—mapping straight onto the Verification and Release stations of the Software Factory (Level 3 → Level 4).
| Verification gate | What it proves | Failure trigger |
|---|---|---|
| Repo-wide type check | Every compiled consumer agrees with the updated contract | Any call site still passes the old shape |
| Affected consumer tests | Downstream behavior holds across dependent packages | Build graph runs tests for every dependent target, not only the edited package |
| Zero-residue search | No legacy field name, string key, or payload property remains | Regex or AST search over code and schemas finds leftover references |
| Report-vs-diff reconciliation | Every file in blast-radius.txt was updated or explicitly excused | Set difference between blast-radius.txt and git diff --name-only contains unexcused files |
| Contract and schema tests | Untyped consumers (JSON events, queues, SQL views) still parse cleanly | Event schema or consumer contract suite fails |
| Fitness functions | Dependency direction and layering stayed intact | Agent added a forbidden cross-package import |
| Independent review pass | A fresh model checked logic bugs static tools miss | Review agent raises a P0/P1 finding |
Attach the blast-radius manifest, gate results, and excused.txt rationale to the pull request’s evidence bundle. Package owners via CODEOWNERS inspect the reconciliation and excused list for their domain rather than reading sixty mechanical diffs. Run npx @wondelai/harness-audit (see Harness Audit) to confirm your repository has the instruction budgets, single-command verification, and worktree isolation large codebases require.
What breaks when agents work in million-line codebases?
Section titled “What breaks when agents work in million-line codebases?”- Stale architecture maps or search indexes after big merges. Agents cite moved or deleted paths. Recovery: Re-index after large rebases or codegen runs, regenerate
docs/architecture/map.md, and inspect its diff. - Invented imports or fabricated counts. An agent guesses a symbol path or answers “how many callers?” without running a command. Recovery: Require locating the definition before writing an import, and accept counts only alongside a reproducible search command.
- One generated file floods the context window. An 8,000-line generated SDK pushes out real invariants. Recovery: Exclude generated artifacts via
.cursorignoreand MCP ignore rules, and direct agents to symbols or narrow line ranges. - Individual slices pass while integration breaks. An untyped subscriber or SQL view depended on the old payload. Recovery: Add a contract test on that boundary, record the consumer under “reads without importing” in
docs/architecture/map.md, and rerun reconciliation. - Agents edit re-exports instead of the source of truth. Dependency direction drifted during exploration. Recovery: Run a read-only dependency-graph pass for the target module and pin the canonical source path in the slice prompt.
- Parallel slices collide on shared helpers. Two concurrent worktrees modify the same utility. Recovery: Assign shared files to a single prerequisite slice and merge it before fanning out dependent packages.
Official docs and next steps
Section titled “Official docs and next steps”- Official references: Claude Code docs, OpenAI Codex docs, Cursor docs, and Model Context Protocol.
- Related guides: legacy modernization with agents, git worktrees for parallel agents, architecture fitness functions, and the evidence bundle.
Did this guide help you?
One tap, no sign-in.
What will you do with it?
How did it read?
What got in the way? Pick any that apply
Your role?
Thanks. I read every answer. Michał Jaskólski
Did this guide help?
One tap each. Close whenever you like.
no sign-in