Repository-Scale Coding Agents: Long Context and Sparse Attention in Practice
Long context is a baseline requirement for coding agents that operate across entire repositories, but simply fitting a large codebase into a model's window does not guarantee good results. This article explains where the cost of long context comes from, how Mixture of Experts and sparse or linear attention help control it, and how to build an index-then-retrieve workflow with context budgeting and verification loops for repository-scale code tasks. It also covers evaluation dimensions, selection guidance, and common misconceptions, so engineering teams can turn long-context capability into reliable code changes.
Repository-Scale Coding Agents: Long Context and Sparse Attention in Practice
1. Why Code Tasks Need Long Context
Coding agents differ from ordinary Q&A systems. They need to understand call relationships between modules, configuration files, test cases, and design documents—and sometimes complete a change that spans dozens of files. If a model can only process a few thousand tokens at a time, it has to infer the global structure from local fragments, which often produces code that is locally correct but globally inconsistent.
Long context is therefore a foundational requirement for these scenarios. However, “being able to fit the input” and “being able to use it well” are two different things. A model that accepts longer inputs will not necessarily locate the key information within them, and the inference cost may not be acceptable. This article explains how to evaluate and use ultra-long context capabilities from three angles: model architecture, inference cost, and engineering methods.
2. Where the Cost of Long Context Comes From
2.1 Attention Computation Grows Quadratically with Length
In standard self-attention, every token computes relevance against every other token in the sequence. For a sequence of length n, the computation is proportional to n². Extending the context by 10x increases the attention computation roughly 100x in theory. This is the root of the long-context cost problem.
2.2 KV Cache Consumes Memory
During inference, the key and value vectors of already-processed content must be cached so they can be reused when generating new tokens. Cache memory usage grows roughly linearly with sequence length. Long context not only slows down individual requests but also consumes significant memory, reducing the number of concurrent requests a device can serve and raising the per-unit cost.
2.3 Two Directions for Reducing Cost
Reducing long-context cost usually requires addressing two things at once: reducing the number of parameters each token activates during computation, and reducing the computation scope of attention or the cache size. Mixture of Experts primarily addresses the former; sparse attention and linear attention primarily address the latter.
3. Mixture of Experts: Controlling Per-Token Compute with Sparse Activation
Mixture of Experts (MoE) splits the feed-forward network into multiple expert subnetworks. A routing module scores each input token and selects only the top-scoring few experts to participate in the computation; the rest stay idle.
This design brings two properties:
- Large total parameters, small activated parameters. The model can retain large knowledge capacity, while each token’s actual computation depends only on the selected experts.
- Partial decoupling of capacity from inference cost. Adding more experts increases capacity without proportionally increasing per-inference compute.
There are clear trade-offs. When routing is imbalanced, some experts become overloaded while others are barely used. In multi-device deployments, distributing data across experts also introduces communication overhead. Here is a simplified top-k routing flow:
for each token x:scores = router(x) # score every expertselect the k experts with the highest scoresweights = softmax(scores of selected experts)output = Σ weights[i] * expert[i](x)
4. Combining Sparse Attention and Linear Attention
4.1 Sparse Attention: Attend to Only Part of the Sequence
Sparse attention restricts what each token can attend to. Common approaches include attending only to a local window, only to a few global anchor points, or to selected historical positions based on preset rules. This reduces computation from n² to roughly n times a constant.
The risk is that long-range dependencies across regions may be missed. For example, if a function is defined at the top of a file and called at the bottom, and the two fall outside the same window, the model may fail to link them.
4.2 Linear Attention: Approximating Full Comparison with a Recurrent State
Linear attention uses kernel-function approximations to rewrite attention as a recurrently updated state. Computation and memory grow roughly linearly with length, offering clear advantages for very long sequences.
Its weakness is precise localization. For tasks that require retrieving one specific piece of content from a large body of text, linear approximation may lose accuracy.
4.3 Hybrid Design
In practice, models often combine both mechanisms. For example, a few layers keep more precise global attention for accurate long-range retrieval, while the majority of layers use sparse or linear mechanisms to reduce overall cost. The ratio and placement of these layers should be tuned to the target task.
Layer structures, ratios, and implementation details vary significantly across specific models—always refer to each model’s published technical report or official documentation. This article covers only general principles.
5. Engineering Practice for Repository-Scale Code Tasks
Even if a model supports ultra-long inputs, stuffing an entire repository into the context is usually not the best approach, for three main reasons: high inference cost, noise from irrelevant content, and too many files distracting the model from the task’s focus.
A more reliable approach is to build an index first, then read the relevant content on demand.
5.1 Building the Index
Index building generally involves four steps:
- Scan the directory structure, skipping build artifacts, dependency directories, and binary files.
- Split code along syntactic structures such as functions, classes, and modules, recording file paths and line ranges.
- Extract symbol definitions and references to form a dependency graph.
- Build both keyword and vector retrieval over the indexed content.
Illustrative pseudocode:
function build_index(repo_root):index = empty indexfor file in walk(repo_root, ignore_rules):if not text file: continuechunks = split_by_syntax(file)for chunk in chunks:index.add(chunk.path, chunk.line_range, chunk.symbols, chunk.summary)index.record_references(chunk.symbols, chunk.referenced_symbols)return indexfunction collect_context(index, task, budget):candidates = index.retrieve(task) # hybrid keyword + vector recallcandidates = add_dependency_definitions(candidates) # include called functions and type definitionscontext = []for c in sort_by_relevance(candidates):if used_tokens + c.length > budget: breakcontext.append(c)return context
5.2 Managing the Context Budget
Context content falls into three tiers, ordered by priority:
- Must keep: task description, acceptance criteria, coding constraints.
- Keep first: the code to be modified and the definitions of its direct dependencies.
- Keep as needed: historical commit messages, design documents, indirectly related modules.
When the budget is tight, trim the third tier first—never the function being modified. If a task needs more context than the budget allows, the better approach is to split the task rather than force-compress the information.
5.3 Incremental Changes and a Verification Loop
Code changes should be controllable and verifiable. Recommended principles:
- Limit each change to a clearly defined scope; avoid touching unrelated code.
- Output patches rather than full-file rewrites, making human review easier.
- Run tests and static checks after each change.
- On test failure, feed the error messages back into the context for the next round of fixes.
- Keep a record of every round of changes so problems can be rolled back.
6. Evaluation Methods
When evaluating long-context solutions, observe four dimensions:
- Retrieval recall: whether the files truly relevant to the task make it into the context.
- Task success rate: whether tests pass after the change and whether acceptance criteria are met.
- Latency and unit cost: response time and compute consumption per task.
- Change scope: whether unrelated modifications were introduced.
Public general-purpose benchmarks are only a reference. More valuable is for a team to assemble a set of tasks with clear acceptance criteria based on its own real repositories, and compare different solutions under identical conditions.
7. Selection and Adoption Advice
- Analyze the real context requirements of your tasks first. Many changes involve only a few files and do not require feeding the whole repository to the model.
- Stress-test long inputs, recording how response time and accuracy change with input length, and identify the acceptable range.
- Build indexing and retrieval as an independent module so the context budget becomes a tunable parameter, making it easier to swap models later.
- Apply desensitization and access controls to sensitive code, sending only authorized content to the model.
- Changes on critical paths must be confirmed by humans; the automated pipeline should only propose solutions and run verification.
8. Common Misconceptions
Misconception 1: Longer context is always better. Too much irrelevant information dilutes the model’s attention to key constraints, and it may ignore the requirements that actually matter.
Misconception 2: A large window makes retrieval unnecessary. A large window solves the “fits in” problem; retrieval solves the “finds the right thing” problem. Both are indispensable.
Misconception 3: Only looking at parameter count. Activated parameters, attention structure, inference framework, and deployment setup together determine the actual experience—total parameter count alone cannot predict results.
Long context gives coding agents a larger working space. Only when model architecture, retrieval strategy, and a verification loop work well together can that space be converted into reliable code changes.
