Developer tools · Research feature

Retrieval-Augmented Code Generation: A Survey with Focus on Repository-Level Approaches

A new survey reviews AI methods that retrieve and analyze code across entire software repositories to improve code generation accuracy and context awareness.

Adapted from research by Yicheng Tao, Yuante Li, Yao Qin and colleagues.

arXiv preprint revision · 2026-05-20 · Attribution & reuse
In this article
Editorial illustration of developer workstation.

Editor’s introduction

The study focuses on Retrieval-Augmented Code Generation (RACG) methods designed to operate at the repository level, where models must retrieve, organize, and reason over distributed code context. The evidence shows that non-graph methods often retrieve fragmented code chunks, while graph-based approaches face high overhead and depend on language-specific parsing tools, limiting their portability. The study highlights that retrieval and generation are typically optimized separately, leading to misalignment between context quality and code output effectiveness.

Challenges

The first challenge is long-range dependency modeling: critical information is distributed across files, documents, and dependencies, while changes in one file may affect distant modules, making it difficult to identify minimal but sufficient context and maintain cross-file consistency. The second is the efficiency–correctness trade-off: issue resolution prioritizes accuracy, whereas real-time completion demands low latency. This trade-off is further complicated by model limitations—strong models may memorize common libraries, while weaker ones suffer from context overload. Scaling model size or context length only partially alleviates these issues and is often impractical for local deployment. Finally, practical constraints further limit applicability: privacy and compliance restrict cloud-based use of proprietary code, and most LLMs are trained in outdated public repositories, reducing adaptability in real-world and enterprise settings.

The above challenges indicate that, in real-world settings, code generation is no longer a simple problem, but a complex process involving context selection and external information acquisition. In this context, Retrieval-Augmented Generation (RAG) offers an effective way to address context limitations by dynamically incorporating external knowledge during reasoning. In the code domain, this paradigm has evolved into Retrieval-Augmented Code Generation (RACG), which enhances generation quality by retrieving relevant code and structural information.

However, in repository-level scenarios, RACG is no longer a simple two-stage “retrieve-then-generate” pipeline. Instead, it becomes a dynamic process that can be coupled with customized indexing and structure-aware retrieval. We characterize RACG as a unified process in which the model (i) constructs and retrieves context from large-scale code repositories, and (ii) generates or modifies code based on the retrieved information and current system state. In addition to this core process, various enhancements—such as iterative refinement, multi-source context acquisition, and tool-assisted reasoning—can be incorporated to improve performance. This formulation naturally aligns with Repository-Level Code Generation (RLCG), which represents a new and challenging problem.

Data Collection Process

In the first stage, we determined our core search keywords by analyzing accepted papers related to this topic. This initial step allowed us to derive and refine a precise set of search terms strongly associated with RACG.

In the second stage, we collected all publications from leading artificial intelligence and software engineering venues and journals (ICLR, NeurIPS, ICML, IJCAI, AAAI, JMLR, ACL, EMNLP, ICSE, FSE, ASE, TOSEM, TSE, and ISSTA). We then conducted keyword similarity searches across multiple bibliographic platforms, including ACM Digital Library, IEEE Xplore, arXiv, OpenReview, and the ACL Anthology. For journals and platforms with anti-crawling mechanisms, we supplemented automated retrieval with manual scanning. For preprints on arXiv, we implemented a hybrid approach: we first queried the arXiv API using the keywords, and subsequently applied similarity filtering to isolate the most relevant papers.

Non-Graph-based RACG

Non-graph-based RAG methods retrieve code without explicit graph structures, treating repositories as flat text collections and identifying relevant context via similarity matching. Early approaches rely on lexical signals (e.g., BM25, Jaccard similarity ) to match identifiers or keywords, but struggle with deeper semantics. Recent systems shift to semantic retrieval using representation learning. Models such as GraphCodeBERT and UniXcoder encode code into embeddings, enabling similarity matching that better captures functional and contextual relationships.

Despite their simplicity, these methods remain widely used due to efficiency and ease of integration. Modern RACG systems extend them along two axes: retrieval strategies (how to search) and retrieval content construction (what to retrieve and how to organize it). Emerging directions further incorporate static analysis for structural signals and command-driven retrieval for dynamic, interactive context acquisition.

Query Reformulation and Multi-Perspective Retrieval

A key issue is the mismatch between query form and code semantics. To address this, methods enhance query expressiveness in two ways. First, multi-perspective enrichment generates complementary query views. ProCC combines lexical, hypothesis, and summary views with bandit selection. RLPG samples candidate contexts and learns selection. ReCo rewrites queries and code for consistency. AlignCoder further leverages multiple candidate completions to construct richer queries. Second, conversion-based retrieval bridges modality gaps. SACL augments code with semantic descriptions. Kondo et al. convert code to natural language. Code2JSON, Chen et al., and CodeBridge explore structured or alternative matching. Li et al. introduce reasoning-based intent synthesis via docstring-like generation.

Multi-Level Graph Integration

A clear trend is the integration of multiple structural levels within a single system, where different graph representations are assigned complementary roles for context resolution. CoSIL adopts a two-stage retrieval pipeline, first locating relevant files via a coarse module-level call graph and then refining context using a function-level graph. LocAgent organizes repositories into a hierarchical dependency graph exposed as an interactive reasoning tool. Beyond structural hierarchies, several frameworks bridge modalities: GraphCodeAgent links requirement-level semantics with code structure, while DraCo and CodeGRAG combine structural topology with semantic data flow to improve retrieval effectiveness. For autonomous exploration, RepoMaster integrates a Hierarchical Code Tree, Function Call Graph, and Module Dependency Graph. GRACE further advances this direction with a multi-level, multi-semantic graph and hierarchical fusion. Finally, GraphLocator constructs a Causal Issue Graph over a Repository Dependency Fractal Structure Graph to explicitly model symptom-to-root-cause paths.

Autonomous Agent Architectures

Although recent RACG methods improve retrieval and context construction, many still operate as static, one-shot pipelines that cannot revise decisions based on intermediate outcomes. This limitation is especially evident in repository-level tasks (e.g., bug fixing and multi-file editing), which require iterative exploration, error correction, and interaction with external signals.

Agent-based architectures address this by enabling iterative decision-making, structured planning, and environment interaction, transforming RACG into dynamic, feedback-driven workflows. This allows models to decompose tasks, adapt retrieval and generation, and recover from errors. Despite broad adoption across domains, the definition of an “agent” remains inconsistent. In this work, we define an agent as a system that perceives its environment, makes decisions via planning or learned policies, and iteratively executes actions to achieve goals without rigid control flow.

Level 1: Partial Agent Systems

Level 1 systems introduce iterative feedback loops, where intermediate signals (e.g., partial outputs, compiler feedback, or retrieved context) refine subsequent steps. Unlike Level 2, they do not require full planning or autonomous control. Architectural interoperability with agent frameworks, such as RepoGraph and RepoLens, does not, by itself, constitute agentic behavior; such systems are therefore more appropriately classified as Level 1.

The other Level 1 systems can be grouped into three patterns. First, self-guided iteration, where model outputs guide retrieval, as in RepoCoder, FT2Ra, and FastCoder. De-Hallucinator further filters hallucinated APIs during iteration. Second, environment-driven feedback, where external signals guide refinement. CocoGen uses compiler feedback, EvoR incorporates execution and web signals, and other works refine outputs using domain constraints or human feedback. Third, coarse-to-fine strategies progressively narrow the search space. CoSIL moves from file-level to function-level reasoning, while APT prioritizes simpler dependencies before complex ones.

Tool-augmented systems

These systems rely on structured tools to navigate repositories, spanning multiple levels of abstraction. At the command level, RepoNavigator uses a jump tool for symbol retrieval, while CodeScout operates purely via Unix terminal commands. At the software engineering level, tools based on Abstract Syntax Trees (ASTs) and the Language Server Protocol (LSP) enable precise static analysis, as seen in RRR, NEMOTRON-CORTEXA, and AutoCodeRover. Graph-based systems such as GraphCodeAgent, LocAgent, and RepoMaster introduce traversal tools for repository graphs. Domain-specific frameworks include RTLFixer (Verilog compiler) and iSWE (CLDK for Java analysis). At the most general level, SWE-agent defines an Agent–Computer Interface, while OpenHands provides a unified environment for command execution, browsing, and editing.

Downstream Tasks

Before the emergence of RLCG, code intelligence research had already explored retrieval-centric tasks such as code search, which evaluates a model’s ability to retrieve or synthesize code from natural language queries, as well as bug or vulnerability detection, which emphasizes identifying issues using retrieved evidence. With the rise of large language models, RLCG shifts the focus toward stronger generation capabilities, integrating retrieval to support reasoning and synthesis rather than serving as the primary objective.

Another important setting is coding ability evaluation, represented by benchmarks such as HumanEval and MBPP. Although less grounded in real-world workflows, these benchmarks provide standardized environments to assess whether RLCG improves reasoning and code synthesis under external knowledge augmentation, and enable controlled comparisons with other techniques such as instruction tuning or chain-of-thought prompting.

Beyond these, RLCG has also been applied to program repair and test generation, which focuses on synthesizing unit tests or assertions. Emerging directions further include theory-to-code translation and repository-level monitoring, editing, and refactoring. Together, these tasks highlight the versatility of RLCG across multiple dimensions of software engineering.

Repository-Level Line Completion

RepoEval (from RepoCoder) includes 1,600 line completions, 1,600 API calls, and 373 function completions from high-quality Python repositories (2022+). It evaluates functional correctness using repository-native unit tests and snapshots (Jan 2023) across line, API, and function levels. RepoBench supports Python and Java, decomposing RLCG into retrieval (RepoBench-R), completion (RepoBench-C), and pipeline (RepoBench-P) tasks. It uses newly crawled GitHub data and evaluates retrieval with Accuracy@k and completion with EM/ES. CrossCodeEval provides 10,000 cross-file completion examples across Python, Java, TypeScript, and C#, using static analysis for import resolution and evaluating in-file, cross-file retrieval, and combined prompt settings.

Repository-Level Function Generation

CoderEval contains 460 real-world problems (Python/Java) across six context levels, focusing on non-standalone functions. It standardizes inputs as “signature + doc + context” and evaluates with Docker-based Pass@k and Acc@k. EvoCodeBench offers 275 Python samples aligned with evolving repositories, incorporating dependency structures and updates; tasks combine natural language requirements, signatures, references, and tests, evaluated by Pass@k and Recall@k. DevEval includes 1,874 manually annotated samples from 117 repositories across 10 domains, requiring function generation with signatures, natural language requirements, and cross-file context.

General-Purpose Coding Benchmarks (Auxiliary Evidence)

These benchmarks are not designed for repository-level or cross-file tasks but are often used to assess base LLM performance or compare augmentation strategies. They provide indirect evidence for RACG effectiveness. Polyglot Leaderboard evaluates multilingual coding under a unified pass@k metric. LiveCodeBench includes 300+ recent problems (2023–2024) for code generation, self-repair, and execution. HumanEval offers 164 Python problems with signatures, docstrings, and tests for pass@k evaluation. MBPP contains 974 beginner-level Python problems described in natural language. CodeXGLUE is a suite of 10 tasks across 14 datasets, covering translation, completion, and more, with unified evaluation and baselines.

Data Source

General-purpose and web corpora. Some methods incorporate external programming-related text. PKG uses Q&A datasets and tutorials as general knowledge, while EvoR integrates heterogeneous web content (e.g., blogs, discussions, documentation, and execution feedback) into a unified, evolving knowledge base.

Repository-level structural and relational knowledge. Several systems exploit relations within or across repositories. A3-CodGen links local context with global module structures and libraries. construct repository knowledge graphs from commits, issues, and files. RepoMaster builds multi-level graphs (e.g., call graphs, dependency graphs) across repositories and retrieves task-relevant components.

Experience and behavior traces. Another line leverages past interaction traces. ContextModule mines real editing behavior, SWE-Exp stores repair trajectories, and ReCode collects buggy–fixed pairs. Beyond code, use human interaction traces (e.g., collaborative building actions) as retrieval signals.

Security and Reliability

The integration of RAG into repository-level development introduces a unique attack surface spanning both the generation and retrieval modules. On the generation side, LLMs risk inheriting insecure coding patterns from their training data, which often contains vulnerable open-source projects. On the retrieval side, knowledge base poisoning is a major concern. For instance, ImportSnare attack demonstrates that crafted malicious documentation can outrank safe resources, leading to the retrieval of harmful contexts. DrainCode introduces LLM-Denial-of-Service, where the model is manipulated into generating excessively verbose code to exhaust computational resources. Furthermore, VenomRACG demonstrates that a poisoned retriever can be trained to prioritize pre-defined vulnerable code when triggered by specific malicious queries.

To mitigate these risks, several safety-driven architectures have emerged. CodeGuarder proposes that retrievers should also inject security knowledge. combine security knowledge injection with a self-feedback loop. RESCUE introduces a systematic defense through a Hierarchical Security Knowledge Base and Hierarchical Multi-faceted Retrieval.

The Necessity Boundary: RAG vs. Long-Context LLMs

The effectiveness of RAG is context-dependent, and retrieval does not always guarantee better performance. Cited researchers show that long-context models can match or outperform RAG on small, well-structured repositories, while RAG becomes advantageous as repository size and complexity increase.

Several studies demonstrate the benefits of retrieval. CodeGen4Libs validates the usefulness of retrieval for library-oriented generation through user studies. Cited researchers show that RAG improves performance on uncommon APIs and remains robust to mild noise, with BM25 performing strongly., and further report consistent gains from retrieval, especially when combined with effective fusion and selection strategies.

Other work explores replacing RAG with stronger long-context modeling. SelectSolve shows that providing the full repository to a long-context model can rival or exceed agent-based systems. Additional approaches use hierarchical summarization, reinforcement learning, or tool-aware training (e.g., SoRFT, CoLT, ToolGen ) to improve context utilization without explicit retrieval.

Limitations of Existing Approaches

Retrieval and context construction remain difficult. Non-graph-based approaches often retrieve fragmented repository chunks that fail to preserve long-range semantic dependencies, while graph-based systems introduce substantial overhead in graph construction and traversal. Their effectiveness also heavily depends on language-specific parsers and static analysis quality, limiting portability across repositories and programming languages. In addition, retrieval and generation are still frequently optimized separately, creating a disconnect between retrieved context quality and downstream generation utility.

Agentic RACG systems often trade adaptivity for efficiency. Recent agent frameworks enable iterative search, planning, and tool usage, but they also introduce substantial context and computation overhead. Multi-step workflows may accumulate noisy context or redundant exploration steps as repositories scale. At the same time, simpler pipelines such as Agentless can achieve competitive performance with significantly lower cost, suggesting that complex agentic workflows are not always necessary.

Current evaluation settings still lack realism and robustness. Most benchmarks focus on relatively small repositories, synthetic tasks, or Python-centric ecosystems, while repository evolution, collaborative workflows, and multi-language dependencies are rarely modeled explicitly. Recent studies further show that static benchmarks may suffer from contamination and benchmark saturation. Moreover, most RACG systems are still evaluated in isolated environments rather than integrated software engineering ecosystems such as IDEs, CI/CD pipelines, and collaborative development workflows.

Future Directions

RACG systems should move beyond text-only repositories toward richer software artifacts. Future systems can leverage issue discussions, documentation, execution logs, commit histories, and architectural diagrams to improve semantic grounding in underspecified or evolving tasks. At the same time, multilingual repository support remains increasingly important, as modern software projects often combine multiple programming languages and frameworks within a single codebase.

Scalable repository-level reasoning and realistic evaluation remain essential research directions. Recent work increasingly explores hierarchical retrieval, memory compression, and long-context reasoning to support repository-scale understanding with manageable computational cost. Meanwhile, future benchmarks should better reflect practical software engineering workflows such as repository evolution, CI/CD integration, package migration, and collaborative development. Beyond pass@k or patch correctness, evaluation should also measure factors such as execution efficiency, integration consistency, maintainability, and developer utility.

Agentic software engineering workflows are becoming a central paradigm for RACG. Recent systems such as SWE-agent, OpenHands, Claude Code, and Codex demonstrate a shift from static retrieval-and-generation pipelines toward interactive software engineering agents capable of repository navigation, iterative refinement, and environment interaction. Retrieval is increasingly treated as an adaptive test-time process, where agents dynamically decide what files or resources to inspect during problem solving. Future RACG systems may further support repository-wide coordinated editing tasks requiring continuous reasoning over inter-file dependencies and evolving repository states.

Conclusion

As software engineering increasingly shifts from isolated code completion toward repository-scale reasoning and autonomous development workflows, Retrieval-Augmented Code Generation (RACG) has emerged as a critical paradigm for enabling large language models to operate effectively in real-world environments. Unlike traditional code generation settings, repository-level scenarios require models to continuously retrieve, organize, and reason over evolving contextual information distributed across files, dependencies, documentation, and execution feedback.

In this survey, we presented a comprehensive review of RACG research with a particular focus on Repository-Level Code Generation (RLCG). We argued that RACG should not be viewed as a static “retrieve-then-generate” pipeline, but rather as a coupled and dynamic process involving context construction, retrieval optimization, generation, and environment interaction. To systematically analyze this rapidly evolving landscape, we introduced a unified analytical framework spanning retrieval substrate, control regime, and evaluation setting. Based on this framework, we organized existing methods across non-graph-based and graph-based retrieval paradigms, training-driven optimizations, and autonomous agent architectures, while also reviewing downstream tasks, benchmarks, and practical system configurations.

Our analysis reveals several emerging trends in the field. First, RACG systems are evolving from similarity-based retrieval toward structure-aware and graph-driven reasoning. Second, retrieval is increasingly becoming an adaptive and agentic process rather than a fixed preprocessing step. Third, autonomous software engineering agents are transforming RACG from passive generation pipelines into interactive systems capable of planning, tool usage, iterative refinement, and environment-aware decision making. At the same time, important challenges remain unresolved, including scalability, retrieval reliability, long-context efficiency, benchmark realism, cross-language portability, and robustness in dynamic repositories.