Skip to content

Million+ 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:

LayerWhat it carriesWhere it livesLoading rule
ArchitectureModule map, dependency direction, cross-service schema rules, single-command checksRoot AGENTS.md, CLAUDE.md, or always-apply Cursor ruleEvery session (keep compact, ≤ 150 lines)
DomainPackage invariants, money/auth rules, local test commandsNested AGENTS.md, .claude/rules/, or glob-scoped .cursor/rules/*.mdcOnly when touching that package
ImplementationTarget files, direct callers, and one reference pattern to imitateRetrieved via symbol navigation or targeted searchOn 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.

Nested rules prevent domain invariants from polluting unrelated sessions, and each tool evaluates them differently:

  • Claude Code: Loads CLAUDE.md upward from the working directory at launch and loads subdirectory CLAUDE.md files 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.md to avoid drift. Check the Claude Code docs for current precedence rules.
  • OpenAI Codex: Automatically loads AGENTS.md from 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/*.mdc with alwaysApply: true (or root AGENTS.md) and domain invariants with globs or description triggers. Commit .cursorignore to exclude generated clients, lockfiles, and snapshots so boilerplate never swamps workspace search. See the Cursor docs for rule frontmatter and ignore syntax.

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:

StrategyBest forTrade-off
Language Server (LSP) MCP (e.g., Serena)Exact symbol resolution, cross-package renames, finding typed callersStays strictly local; requires healthy language servers per stack
Tree-sitter / call-graph MCPFast structural graphs and call-path tracing across polyglot reposStays local; misses runtime reflection and untyped event payloads
Hybrid vector + BM25 search MCPConceptual questions (“where do we retry failed charges?”) when naming is inconsistentRequires 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.

  1. 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.
  2. 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 FILES list and rank the five riskiest files. If a known consumer is missing, stop and fix indexes or ignore rules first.
  3. Mutate shared contracts first. Commit blast-radius.txt on the feature branch, then update shared types, schemas, and migrations in slice 1 so compiler errors produce an independent consumer list.
  4. 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).
  5. 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 gateWhat it provesFailure trigger
Repo-wide type checkEvery compiled consumer agrees with the updated contractAny call site still passes the old shape
Affected consumer testsDownstream behavior holds across dependent packagesBuild graph runs tests for every dependent target, not only the edited package
Zero-residue searchNo legacy field name, string key, or payload property remainsRegex or AST search over code and schemas finds leftover references
Report-vs-diff reconciliationEvery file in blast-radius.txt was updated or explicitly excusedSet difference between blast-radius.txt and git diff --name-only contains unexcused files
Contract and schema testsUntyped consumers (JSON events, queues, SQL views) still parse cleanlyEvent schema or consumer contract suite fails
Fitness functionsDependency direction and layering stayed intactAgent added a forbidden cross-package import
Independent review passA fresh model checked logic bugs static tools missReview 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 .cursorignore and 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.

Did this guide help you?

One tap, no sign-in.

not at all a lot