Originally published on Medium. This version is now archived under
/blogs.
Picture two developers sitting next to each other, both asking their AI coding agent to refactor the same payment service.
Developer A’s agent, running with default settings and grep-based retrieval, burns through 117,000 tokens just to find the right files, chewing through half its context window before writing a single line of code. Developer B’s agent, built on structural code analysis, finds the same files using 8,500 tokens and 4% of its context window, then gets straight to work.
The task and model quality are identical, but the cost differs by 14x and the speed scales proportionally.
The industry conversation around coding agents has fixated on model intelligence, as if the bottleneck is whether the model can reason well enough. Benchmarking data from recent exploratory studies tells a different story. The ceiling on agent performance is almost entirely determined by how the agent retrieves context from your codebase, before the model ever sees a single token. A brilliant model fed garbage context will produce brilliant garbage.
Four retrieval paradigms now compete for that context window, and each one makes a fundamentally different bet on how machine intelligence should read human code. Each one also has a blind spot that the others were built to cover.
Grep
Terminal-native agents started with the most intuitive approach, and many still default to it. Tools like Claude Code and Gemini CLI hand the model a set of shell tools (grep, ripgrep, find, cat) and let it explore the repo the way a new hire would on day one, poking around directories, searching for keywords, reading files one at a time, building context through repetition.
The appeal is genuine: zero indexing, zero setup, and every retrieval step is a human-readable terminal command you can audit. The agent clones your repo and starts working immediately.
The cost becomes apparent quickly. Imagine you ask the agent to modify the “authentication flow.”
Your codebase, written by three different teams over four years, calls that logic verify_token in the auth service, session_middleware in the Express layer, and OAuth_Handler in the identity provider. A grep search for “authentication” returns zero useful results, and the agent is stuck before it writes a single line of code, defeated by the gap between what you said and what the code is named.
Even when grep lands on relevant matches, it lands on too many. Searching for user_id in an enterprise monorepo is like searching for “the” in a novel. Every migration, analytics script, logging wrapper, and frontend component containing that string comes back. The agent has to load the surrounding context of each match into the model just to figure out which ones matter, which means dumping massive walls of raw text into the context window.
Benchmarking data puts numbers on this. In its default grep-only configuration, Claude Code consumes 108,000 to 117,000 tokens during complex search operations, saturating over half its context window just to locate files. Gemini CLI lands at 102,000 tokens, depending heavily on cache hits to keep costs sane. Developers on engineering forums call this the “time tax.” One GitHub issue documented a repo-wide method rename that took “many hours” through bash tooling, when a traditional IDE refactoring tool could have done the same job deterministically in minutes.
Note: Those numbers reflect Claude Code running without LSP. Since version 2.0.74, Claude Code ships with native LSP support through a plugin system, but it requires manual opt-in (ENABLE_LSP_TOOL=1 plus language server binaries), which means most users and most benchmarks are still measuring the grep-only path. The structural search section below covers what LSP adds and where it fits in the broader retrieval landscape.
RAG
Retrieval-Augmented Generation solves the naming problem that kills grep. By embedding your codebase into a vector database, RAG systems like Cursor, Sourcegraph Cody, and GitHub Copilot can match conceptual intent to code that shares zero literal string overlap with the query.
This is where the paradigm earns its reputation. You search for “database connection retry logic” and the system retrieves a function called establish_pg_pool_with_backoff. The vector embeddings capture the semantic relationship between what you asked and what the code does, despite zero keyword overlap. Comparative benchmarks suggest token usage drops 30% to 40% relative to brute-force grep, and retrieval happens in milliseconds.
Mature RAG systems for code are also more sophisticated than the standard “chunk and embed” pipeline. Cursor, for example, uses AST parsing to chunk code along logical boundaries (classes, methods, functional blocks) rather than naive character-count splits that might bisect a function between its signature and its return statement. Merkle-tree-based synchronization keeps the index current as files change locally.
Interestingly, the failure mode is subtle and devastating. Walk through a concrete scenario: the agent needs to generate a unit test for a method that accepts a custom UserAuth object. RAG retrieves the method itself based on semantic similarity, but UserAuth is defined in a different file, implements an interface in a third file, and requires a factory module in a fourth file to construct valid instances. None of those files share semantic keywords with the query, so they go unretrieved. The LLM, seeing a UserAuth parameter with no definition in context, does what LLMs do and invents one. The generated test compiles against a type that doesn’t exist in your codebase.
This happens because vector embeddings capture conceptual similarity without tracing structural wiring. Software runs on rigid compiler-enforced relationships (class inheritance, interface implementations, generic type constraints, explicit imports) and when a RAG system maps your repo into a latent space, those structural connections get severed. A growing number of senior engineers argue that this failure mode is inherent to the vector-only paradigm, since human developers navigate codebases by tracing imports and following dependency chains rather than querying high-dimensional similarity spaces.
GraphRAG
GraphRAG sits between vector search and compiler-level analysis. Where standard RAG embeds code chunks as isolated points in space, GraphRAG extracts entities (functions, classes, modules) and their relationships (calls, imports, inherits, implements) into a structured knowledge graph. Retrieval works through graph traversal rather than similarity matching, which means the system can follow chains of connection across the codebase.
The practical difference shows up in exactly the scenario where vector RAG failed. When you query for UserAuth, a graph-based retriever walks the edges from that class to its interface, its factory, and its dependent types, following the same logical chain a developer would follow but encoded as structured data rather than reconstructed from text each time.
Tools like Code-Graph-RAG use Tree-sitter to parse multi-language repositories and build these knowledge graphs, exposing them through MCP servers for agents to query with natural language. Microsoft’s GraphRAG framework takes a similar approach at the document level, using community detection algorithms to group related entities into hierarchical clusters.
Where GraphRAG earns its place is in cross-cutting concerns. Two microservices communicate over a network using the same JSON payload but never import each other. Grep cannot find a textual connection, and structural search cannot trace an import that doesn’t exist. A knowledge graph that has extracted both services’ data contracts as entities, with edges linking them to the shared schema, can surface that relationship through traversal.
The trade-offs are real.
- Building the knowledge graph is expensive in both compute time and LLM calls for entity extraction. The graph can drift out of sync as the codebase changes, and re-indexing is slower than a Merkle-tree diff on a vector store.
- For simple, localized queries (“what does this function return?”), graph traversal adds latency without improving retrieval quality.
Structural search
The fourth paradigm rejects treating source code as text, vectors, or even entity graphs. Structural search treats code the way a compiler or parser treats it: as a graph of deterministic dependencies that can be traversed without ambiguity. Two mechanisms operate under this umbrella, at different depths of analysis.
AST-based repo-maps represent the lighter-weight approach. Aider is the clearest example. When it initializes in a project, it uses Tree-sitter to perform a syntactic parse of the entire repository, extracting all class definitions, function signatures, and dependency edges (imports, exports). It synthesizes this into a compressed “repo-map” that gives the LLM a complete bird’s-eye view of the project topology without loading any function bodies into the context window. Think of it as handing the model the table of contents and the index of a book instead of the full text.
Walk through the workflow. You ask Aider to modify a payment processing service. The repo-map shows the graph distance from that service to every other file in the project. It identifies that the service implements PaymentGatewayInterface, depends on TransactionValidator, and returns a PaymentResult type defined in a shared models module. All three files are retrieved before the LLM generates a single token, because the dependency graph made the requirement explicit and eliminated the need for guessing or broad searching.
The token economics tell the story. Aider consistently uses 8,500 to 13,000 tokens per task, representing 4% to 7% context window utilization. Developers routinely note that complex tasks on Aider cost a fraction of a cent while heavier IDEs can burn through daily API limits in a single session.
Tree-sitter parses syntax, though, which means it can identify that file A has an import statement referencing file B, but it cannot resolve symbols through re-exports, aliased imports, or type inference chains. That deeper resolution is where the Language Server Protocol comes in.
LSP-based resolution operates at the semantic level. A language server (pyright, gopls, typescript-language-server) performs full type checking and cross-file symbol resolution, providing the same go-to-definition, find-all-references, and hover-for-type capabilities that power modern IDEs. The LspRag framework demonstrated what happens when you plug this directly into the LLM prompt pipeline: when the agent needs to generate a unit test and encounters a custom UserAuth parameter, the LSP resolves the exact file and line number where UserAuth is defined, follows the chain to its interface and factory, and injects those schemas into context. The entire chain is resolved through deterministic compiler-level navigation rather than vector similarity.
The empirical results from LspRag are striking: up to 213% improvement in generated test coverage for Java, 174% for Golang, and 31% for Python compared to the best-performing RAG baselines. The language-specific gap is telling. Java, with its deep inheritance hierarchies and complex interface patterns, benefits enormously from exact dependency tracking because vector search routinely loses the thread of a factory pattern. Python’s flatter architecture narrows the gap, but the improvement remains significant.
Claude Code’s LSP plugin system (introduced in v2.0.74) brings this same capability into a terminal agent, layering LSP resolution on top of its existing grep-based workflow. The combination gives the agent both the exploratory flexibility of grep and the precision of compiler-level symbol navigation.
Those numbers make structural search look like the obvious winner, so it is worth understanding where it falls short.
Both AST and LSP approaches are anchored to explicit, statically analyzable relationships. If two files share a conceptual relationship but never import each other, neither mechanism will connect them. This sounds like a niche edge case until you consider what it actually rules out: microservices communicating over HTTP, configuration files that govern runtime behavior, documentation that describes architectural intent, dynamically dispatched code (Python’s getattr, Java reflection, Ruby’s method_missing), and any relationship that lives in a developer’s head but never appears in an import statement. In a large organization where services are decoupled by design, these implicit connections are often the ones that matter most during cross-team refactors.
The repo-map approach also has a cold-start cost that the token numbers obscure. Aider’s initial AST parse of a large repository is fast relative to building a vector index, but it still scales with repo size, and the compressed map itself consumes context tokens. For very large monorepos, the map can eat into the same context budget it was designed to protect. And because the map only contains signatures and dependency edges, the LLM still lacks implementation detail until specific files are loaded. If the task requires understanding the logic inside a function rather than its position in the dependency graph, the repo-map provides the address without the contents.
Language support is another practical constraint. Tree-sitter grammars and LSP backends vary widely in maturity. TypeScript, Java, Go, and Python have excellent tooling, but less mainstream languages, polyglot repositories mixing configuration DSLs with application code, or codebases heavy on code generation can leave structural search with an incomplete or misleading graph.
Structural search is the most precise retrieval paradigm available, but the share of a given codebase that lives outside its field of vision determines how far that precision alone can carry an agent.
The convergence
No single paradigm handles the full problem space, and the benchmarking data makes the gaps obvious.
The frontier has moved toward multi-engine architectures that route queries based on their nature. The pattern emerging across the best-performing systems is layered: structural search (AST repo-maps for topology, LSP for precise symbol resolution) handles local, syntactical context where determinism matters. Semantic vector search covers global, conceptual context where the query and the code share intent but not vocabulary. GraphRAG fills the middle ground for cross-cutting relationships that are too implicit for structural analysis but too structural for pure similarity matching. Grep remains the universal fallback for real-time file state and ad-hoc exploration where no index exists yet.
The Model Context Protocol (MCP) is accelerating this convergence by giving a single agent the ability to simultaneously query an LSP server for symbol resolution, a knowledge graph for architectural patterns, a vector database for conceptual search, and a shell for real-time file state. Meanwhile, compression middleware like SWE-Pruner uses small local models to prune irrelevant syntax before it reaches the expensive frontier model, achieving 40% token savings without degrading task success rates.
The competitive moat in AI-assisted development is shifting. Larger context windows and faster models help at the margin, but the defining capability is context engineering: the orchestration of multiple retrieval strategies into a single cost-efficient pipeline that knows which tool to use for which kind of question. The agent that picks the right retrieval strategy for each sub-problem will consistently outperform the agent that defaults to one paradigm for everything, regardless of how good that default paradigm is.
The trajectory is clear. Even tools that started with grep-only retrieval are adding structural layers, and the ones that treat all four paradigms as composable building blocks will pull ahead fastest.
Data referenced in this article is drawn from “An Exploratory Study of Code Retrieval Techniques in Coding Agents” (Preprints.org, 2025), the LspRag paper (arXiv, 2025), and publicly available developer benchmarks and forum discussions.