Long-Context LLMs for Full-Repository Code Review Agents: An Engineering Practice
This article explains how to build a full-repository code review agent powered by long-context large language models. It covers repository scanning and filtering, context assembly, model API integration, review-specific prompting, cost and security controls, incremental review, and the limitations of full-context injection. The approach favors a simple architecture without vector databases or retrieval pipelines, making it practical for small and medium-sized codebases.
1. The Starting Point: Limited Context Sets the Ceiling for Review Quality
Traditional approaches provide a model with a single file or a small group of related files for review. The model sees isolated code, but not cross-module call relationships, interface contracts, or the business reasons behind historical changes. As a result, its recommendations often remain at the syntax and style level. A typical suggestion might be, “This method could be extracted into a utility class,” even though the project already has an equivalent utility class in another package.
Suggestions like these are difficult to apply and gradually reduce reviewers’ trust in the system.
The underlying problem is not necessarily a lack of model capability. It is incomplete context. Code review depends heavily on global information. To determine whether a change is safe, the reviewer needs to know who calls it. To assess whether a name is appropriate, the reviewer needs to understand the project’s existing terminology. To evaluate exception handling, the reviewer needs to know the error-code conventions used by higher layers. Without this information, the model can only make local inferences.
2. The Capability Prerequisite: Long Context Changes the Cost Structure
Over the past two years, general-purpose large language model services have expanded their context windows to the million-token range, while inference costs per token have continued to decline. Together, these changes make “put the entire repository into the context” more than an expensive experiment. It can now become part of a routine engineering workflow.
For small and medium-sized projects with fewer than 100,000 lines of code, injecting the complete repository can be feasible in both context size and budget.
This does not mean that everything should be inserted without filtering. As the context grows, attention can become diluted, while first-token latency and cost also increase. The engineering question has therefore shifted from “Can the repository fit?” to “How can the most valuable information be included within the available budget?”
3. Goals and Scope
The agent should perform five tasks:
- Recursively read all code files under a specified directory.
- Filter out files that do not need review, such as build artifacts, dependency directories, configuration files, and binary resources.
- Assemble the code into context with path and structural markers.
- Generate task-specific prompts for different review modes, including full, single-file, security, and performance reviews.
- Call the language model and stream the review results.
The architecture is deliberately simple. It does not introduce a vector database, retrieval-augmented generation, or semantic indexing. Full-context injection is itself a “brute-force but precise” retrieval strategy. It avoids the engineering complexity and potential recall loss associated with chunking, embedding, retrieval, and reranking.
The core implementation is approximately 200 lines of code.
4. The Integration Layer: Decoupling the Model Service
The integration layer depends only on the HTTP client included in the JDK. The service URL, API key, and model name are injected through configuration, making it easier to switch between model providers.
Major cloud platforms, including Baidu AI Cloud, provide large-model access capabilities with broadly similar API patterns. In many cases, migration mainly requires configuration changes.
public record ModelConfig(String baseUrl, String apiKey, String model,double temperature, int maxTokens) {}public class ChatClient {private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();private final ModelConfig cfg;public void stream(String system, String user, Consumer<String> onDelta) throws Exception {String body = """{"model":"%s","temperature":%s,"max_tokens":%d,"stream":true,"messages":[{"role":"system","content":"%s"},{"role":"user","content":"%s"}]}""".formatted(cfg.model(), cfg.temperature(), cfg.maxTokens(),esc(system), esc(user));HttpRequest req = HttpRequest.newBuilder().uri(URI.create(cfg.baseUrl() + "/chat/completions")).header("Authorization", "Bearer " + cfg.apiKey()).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body)).build();http.send(req, HttpResponse.BodyHandlers.ofLines()).body().stream().filter(l -> l.startsWith("data: ") && !l.contains("[DONE]")).map(l -> l.substring(6)).map(this::delta).forEach(onDelta);}}
Two practical parameter guidelines are especially important:
- Code review requires stable and reproducible conclusions, so the temperature should generally be kept around 0.2–0.3.
- Set the output limit according to the expected length of a single review. In many cases, 8192 tokens is sufficient.
If the selected model service provides only a conversational API and does not support embeddings, embedding-related initialization should be explicitly disabled in the configuration. This prevents startup failures caused by unnecessary vector capability initialization.
5. The Repository Reader: Filtering Rules Determine the Signal-to-Noise Ratio
The repository reader is the most important piece of infrastructure in the system. It converts a directory tree into structured text, and the quality of its filtering rules directly determines the signal-to-noise ratio of the context.
public record RepoFile(String path, String content) {}public class RepoScanner {private static final Set<String> SKIP_DIRS = Set.of(".git", "target", "build", "node_modules", "dist", ".idea", ".venv");private static final Set<String> SKIP_EXT = Set.of(".class", ".jar", ".war", ".lock", ".min.js", ".map",".png", ".jpg", ".gif", ".svg", ".pdf", ".zip");private static final long MAX_BYTES = 200 * 1024;public List<RepoFile> scan(Path root) throws IOException {try (var walk = Files.walk(root)) {return walk.filter(Files::isRegularFile).filter(p -> !skip(root, p)).filter(p -> Files.size(p) <= MAX_BYTES).sorted(comparing(p -> root.relativize(p).toString())).map(p -> new RepoFile(root.relativize(p).toString(), read(p))).toList();}}}
Filtering should generally cover four categories:
- Version-control and dependency directories.
- Build artifacts.
- Generated code and compressed or binary resources.
- Oversized individual files.
The scanner should also support whitelist and blacklist rules through configuration files. This allows filtering policies to evolve with the project without requiring code changes.
Files should be decoded consistently as UTF-8. If decoding fails, the scanner should skip the file instead of aborting the entire process.
6. Context Assembly: Budget Management and Structural Markers
The assembly stage introduces a character budget. As a rough guideline, one Chinese character corresponds to approximately one to two tokens, while four English characters correspond to approximately one token. A 20% reserve should be maintained to account for estimation errors and additional prompt content.
The system should first add the task description and repository structure, then expand file contents in lexicographic path order. When the budget is exhausted, the remaining content should be truncated and the model should be explicitly informed.
public String assemble(String task, List<RepoFile> files, int budget) {var sb = new StringBuilder();sb.append("## Review Task\n").append(task).append("\n\n## Repository Structure\n");files.forEach(f -> sb.append("- ").append(f.path()).append('\n'));sb.append("\n## File Contents\n");int used = sb.length();for (RepoFile f : files) {int cost = f.content().length() + f.path().length() + 64;if (used + cost > budget) {sb.append("\n<!-- The remaining ").append(files.size()).append(" files were not expanded because of the budget limit -->\n");break;}sb.append("\n### FILE: ").append(f.path()).append("\n```\n").append(f.content()).append("\n```\n");used += cost;}return sb.toString();}
Structural markers such as ### FILE: and code fences help the model reliably reference specific file paths. They also make it easier to aggregate findings by file later.
The truncation notice is essential. Without it, the model may interpret “not provided” as “does not exist,” causing it to miss issues without realizing that the relevant code was outside its context.
7. Generate Prompts by Review Type
The same repository context can support different requirements when combined with task-specific prompts.
| Review Type | Input Scope | Focus Areas |
|---|---|---|
| Full review | Entire repository | Layering, module responsibilities, duplicate implementations, naming consistency |
| Single-file review | Target file and referenced components | Logic correctness, edge cases, readability |
| Security review | Entire repository and entry-point inventory | Injection, privilege escalation, hard-coded secrets, dependency risks |
| Performance review | Files related to hot paths | Remote calls inside loops, N+1 queries, unbounded collections, lock granularity |
All prompts should require findings in the following format:
File and line number — Issue — Evidence — Recommendation
The prompt should also prohibit speculation about code that was not provided. When the model cannot determine something reliably, it should explicitly mark the item as requiring human confirmation.
Constraining the output format is important for reducing hallucinations and improving aggregation across reviews.
8. Engineering Considerations
- Incremental review: For daily development, review only files changed in version control and their direct dependencies. Reserve full-repository reviews for pre-merge checks and periodic inspections.
- Caching and deduplication: Cache review results using the file-content hash as the key. Unchanged files should not incur repeated inference costs.
- Cost control: Record input and output token usage and request latency for every call. Set daily budget alerts, and switch to a stronger reasoning model only for complex architectural analysis.
- Security and compliance: Review context contains the entire source codebase. Secrets must be supplied through environment variables or a secret-management service, and logs must be sanitized. Organizations should clearly define whether source code may leave the internal network or tenant boundary.
- False-positive management: Build an annotated evaluation set and measure the system continuously. Add prompt constraints for frequently misclassified issues, and position the agent as a tool that raises concerns rather than one that makes final judgments.
9. Limitations and Future Evolution
The boundaries of full-context injection are clear. Very large repositories, mixed-language codebases, and scenarios requiring cross-service call-chain analysis can exceed available context windows and budgets. These cases require a hybrid approach based on structural indexing and on-demand retrieval.
Models also have limited awareness of implicit conventions, such as team standards and historical architectural decisions. Including architecture decision records and coding guidelines alongside the source code is one of the most direct ways to improve the adoption rate of review recommendations.
