Enterprise codebases do not fit into context windows. A production monorepo can easily span tens of millions of lines of code across tens of thousands of files. Even if an LLM boasts a theoretical 1-million-token context window, dumping an entire repository into a prompt is an architectural dead end. It is painfully slow, prohibitively expensive, and plagued by the "lost-in-the-middle" attention degradation that causes models to hallucinate APIs or ignore critical business logic.
At 365Finds, we frequently encounter engineering teams who assume AI coding assistants rely purely on dense vector databases—chunking millions of files, calculating embeddings, and hoping cosine similarity finds the right lines. Sourcegraph Cody actually started down that path during its early development. Then, Sourcegraph realized that pure vector retrieval breaks under real-world enterprise conditions.
To index massive codebases without suffocating large language models or blowing through token budgets, Sourcegraph Cody deploys a hybrid retrieval architecture. It combines trigram keyword indexing via Zoekt, structural code intelligence, selective semantic search, and aggressive snippet-level token budgeting. Here is how Cody solves the codebase scale problem without hitting token limits, and what engineering leaders need to know before deploying it.
The Failure of Pure Vector Embeddings at Scale
During Cody's early beta phases, Sourcegraph relied heavily on dense vector embeddings (such as OpenAI's text-embedding-ada-002) to handle retrieval-augmented generation (RAG). On paper, vector embeddings sound ideal: turn code into mathematical vectors and match natural-language queries to conceptually similar code blocks.
In enterprise environments with tens of thousands of repositories, this pure-vector approach ran into three critical barriers:
- The Compliance and Security Gate: Calculating embeddings for billions of tokens meant streaming proprietary source code to third-party embedding APIs. For regulated industries and security-conscious enterprises, this was an immediate blocker.
- Operational Overhead and Stale Indexes: Repositories move fast. Every commit, merge, and branch rebase invalidates parts of the vector index. Re-indexing tens of millions of lines continuously incurs immense computational costs and creates lag between committed code and AI awareness.
- The Lexical Precision Problem: Code is not natural language. Code punishes fuzzy similarity. If a developer searches for an exact function signature, an unusual error constant, or an obscure interface name, cosine similarity often returns semantically related prose while missing the exact symbol definition. Furthermore, arbitrary chunking splits function definitions from their call-sites, destroying syntactic relationships.
Recognizing these limitations, Sourcegraph pivoted. Instead of forcing vector databases to do a job they were never designed for, Sourcegraph connected Cody directly to its existing, battle-tested enterprise search engine.
The Engine Room: Zoekt Trigram Search Meets Code Graph
The core technical advantage of Sourcegraph Cody is Zoekt, an open-source, high-performance trigram code search engine originally developed by Han-Wen Nienhuys and heavily maintained by Sourcegraph.
Zoekt does not store high-dimensional floating-point vectors. Instead, it builds an inverted index based on character trigrams (sequences of three consecutive characters) mapped into memory using memory-mapped files (mmap). This allows Zoekt to execute exact token matching, regular expressions, and structural symbol queries across petabytes of code in sub-second time.
When Cody indexes a massive codebase, it constructs a multi-layered search index:
- Trigram Indexing (Zoekt): Scans the entire enterprise codebase to index file paths, symbols, method declarations, and textual tokens. Zoekt handles the heavy lifting of multi-repo discovery across GitHub, GitLab, and Bitbucket hosts without requiring GPU acceleration.
- Structural Code Intelligence (SCIP & Tree-sitter): Rather than treating code as raw text, Cody leverages abstract syntax trees (ASTs) and Sourcegraph's SCIP (Source Code Intelligence Protocol) index. This enables Cody to understand precise definitions, hover documentation, and inbound/outbound reference graphs across files.
- Selective Semantic Embeddings: Embeddings are not completely eliminated; instead, they are demoted from the sole indexing mechanism to an optional semantic supplement. They are reserved for high-level conceptual questions (e.g., "where is the token refresh retry loop implemented?") where the developer does not know the exact symbol name.
By making Zoekt and structural graph indexing the primary retrieval layer, Cody avoids the multi-gigabyte vector index overhead and keeps latency within interactive editor tolerances.
The Context Pipeline: How Cody Beats Token Limits
Indexing massive repositories is only half the battle. The other half is packing the most relevant pieces of that index into a strict LLM token window. Cody accomplishes this through a deterministic five-stage context funnel.
[ Developer Prompt ]
│
▼
[ Query Rewriting & Token Extraction ]
│
▼
[ Hybrid Retrieval: Zoekt + SCIP + Local Workspace ]
│
▼
[ AST-Level Snippet Extraction & Pruning ]
│
▼
[ Relevance Scoring & Greedy Token Budget Packing ]
│
▼
[ Augmented Prompt to LLM (Claude / GPT-4o) ]
1. Query Rewriting and Token Extraction
When you ask Cody a question in your IDE, it does not send your raw prose directly to an LLM. Cody's client and server inspect the prompt, extract potential code identifiers, parse file path hints, and formulate optimized search queries tailored for Zoekt.
2. Multi-Source Retrieval
Cody simultaneously queries two distinct environments:
- Remote Sourcegraph Search: Zoekt runs fast regex and symbol queries across all repositories indexed on your enterprise instance.
- Local Workspace State: The IDE plugin evaluates active editor tabs, visible code ranges, cursor positions, and recent Git diffs. 365Finds finds this local-remote pairing critical: the active file provides immediate intent, while remote Zoekt provides deep architectural grounding.
3. AST-Level Snippet Pruning
A common mistake in naive RAG tools is injecting whole files into the prompt. If Cody identifies an 8,000-line controller file as relevant, sending that entire file would consume half of a typical context window and introduce immense noise.
Instead, Cody parses the file's syntax tree to extract only the target function definition, its immediate docstring, relevant import headers, and surrounding type signatures. Unrelated methods in the same file are aggressively discarded.
4. Strict Token Budgeting and Greedy Packing
Cody operates with a strict, pre-allocated token budget for its prompt payload. The budget is segmented into distinct buckets:
- System Prompt & Instructions: Fixed overhead.
- Conversation History: Slotted with exponential decay to preserve recent turns.
- Retrieved Code Context: Typically allocated between 7,000 and 30,000 tokens depending on the active model backend (e.g., Claude 3.5 Sonnet or GPT-4o).
Cody scores all retrieved code snippets using a modified BM25F ranking algorithm combined with structural proximity scores. It then greedily packs the highest-scoring snippets into the context pool until the token ceiling is reached. Any lower-ranked snippets are cleanly dropped. This ensures the LLM receives maximum signal density without overflowing the context window.
5. Explicit Context Steering (@-mentions)
Heuristic retrieval can occasionally miss nuances in complex, cross-module refactors. Sourcegraph mitigates this by giving developers deterministic override controls via @-mentions:
@fileattaches exact file contents (or AST-pruned ranges).@symbolretrieves the exact declaration and references of a class, function, or interface.@folderscopes search directly to a specific microservice or package.@repoforces Zoekt to pull context from a remote repository outside the immediate local workspace.
When a developer uses an @-mention, Cody bypasses speculative search and prioritizes those exact tokens in the budget allocation.
365Finds Institutional Evaluation
365Finds favors Sourcegraph Cody's architectural direction over the vector-only RAG patterns popular in earlier AI assistants. Sourcegraph made the pragmatic choice: code is structured, exact, and hierarchical, and Zoekt's trigram indexing paired with AST pruning provides far more reliable grounding than high-dimensional cosine similarity.
However, engineering teams should evaluate two critical caveats:
- The Local-Only Gap: Cody’s full context prowess depends heavily on a connected Sourcegraph Enterprise instance. When used in standalone local mode without an enterprise server, Cody falls back on simpler local keyword scanning or local vector caches. In large monorepos, local-only performance is visibly less comprehensive than remote Zoekt-backed retrieval.
- Context Truncation on Deep Call Graphs: While Cody's token budgeting prevents model overflow, greedy snippet pruning can occasionally drop distant call-chain dependencies in deeply nested architectures. For mission-critical tasks, developers should actively combine Cody's automatic search with manual
@symbolmentions to ensure complete context chains.
Sourcegraph Cody proves that conquering token limits does not require brute-forcing million-token context windows. By combining trigram indexing, structural code intelligence, and disciplined token budgeting, Cody indexes enterprise-scale codebases efficiently while delivering precise, hallucination-resistant answers.