AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Sourcegraph Cody Indexes Repositories for Contextual Autocomplete

高岡さゆり · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Marketing brochures make AI code autocompletion sound like telepathy: you type two keystrokes, and a model supposedly queries billions of tokens across twenty corporate microservices, computes dense vector embeddings on the fly, and deposits the exact function signature you needed into your editor.

At 365Finds, we look at engineering reality rather than marketing claims. If an AI coding assistant performed a multi-repository vector similarity search on every keystroke, your IDE would grind to a halt. Autocomplete requires an end-to-end response budget under 200 to 400 milliseconds. Network roundtrips to an embedding database across the globe simply cannot fit into that window.

Sourcegraph Cody takes a fundamentally different, hybrid approach. Cody splits context retrieval into two distinct tiers: an ultra-fast local tier running directly in your IDE (driven by Tree-sitter parsing, Jaccard token heuristics, and a local symbol indexer called symf), and an enterprise remote tier (anchored in Sourcegraph’s Zoekt trigram search and SCIP code graphs).

Here is an architectural breakdown of how Sourcegraph Cody indexes local and remote repositories, how it feeds that context into autocomplete prompts, and how engineering teams should configure it to maximize completion accuracy without sacrificing typing speed.


1. The Context Split: Local IDE vs. Remote Codebase

To understand Cody’s autocomplete, you must discard the idea that autocompletions and chat prompts work the same way. In chat, Cody has seconds to query Sourcegraph instances, run semantic searches, expand @-mentions, and compile comprehensive prompt context. In autocomplete, Cody has tens of milliseconds.

+-------------------------------------------------------------------+
|                        Your IDE (Editor)                          |
|                                                                   |
|   Active Buffer (Cursor)  <--- Tree-Sitter AST Parse (<15ms)      |
|          |                                                        |
|          +--> Fill-in-the-Middle (FIM) Prefix / Suffix Extract     |
|          |                                                        |
|   Neighboring Tabs        <--- Jaccard Token Overlap Heuristics   |
|   Workspace Files         <--- symf Local Symbol Search Engine     |
+----------------------------------+--------------------------------+
                                   | Local Context (<50ms)
                                   v
+----------------------------------+--------------------------------+
|                 Cody Context Assembly Pipeline                    |
|                                                                   |
|   [Optional: Cached Remote Symbols via Zoekt / SCIP Graph]        |
|                                                                   |
|          Combined Context Snippets + FIM Prompt                   |
+----------------------------------+--------------------------------+
                                   | Streaming Request
                                   v
+----------------------------------+--------------------------------+
|            Completions LLM (e.g., DeepSeek-Coder-V2)             |
|                                                                   |
|   Ghost Text Prediction Streamed Back to Editor Buffer            |
+-------------------------------------------------------------------+

The Local Tier: Fast, Structural, and Zero-Roundtrip

When you type inside VS Code or JetBrains, Cody gathers immediate context right on your workstation:

  1. Tree-sitter Syntax Scoping: Cody does not treat your code as raw string blobs. It runs incremental Tree-sitter parsers to analyze the concrete syntax tree around your cursor. It knows whether your cursor sits inside an import statement, a class inheritance definition, a function parameter list, or an asynchronous loop. This structural parsing tells the completion engine what syntax constructs are legally allowed to follow.
  2. Fill-In-The-Middle (FIM): The editor splits the active document into two slices: prefix (everything before the cursor) and suffix (everything after). Modern completions models accept special FIM tokens (<PRE>, <SUF>, <MID>), allowing Cody to generate code that fits naturally into the existing code block rather than merely appending text.
  3. Neighboring Buffer Scans (Jaccard Similarity): Cody evaluates your open editor tabs and recently visited buffers. Instead of running computationally heavy transformers locally, it uses lightweight token-matching algorithms like Jaccard similarity. If you are writing a controller in user_controller.ts and have user_model.ts open in another tab, Cody detects shared identifiers (types, interface names, imports) and extracts the relevant snippets into the prompt.
  4. Local Symbol Search (symf): For codebase lookups that exceed open tabs, Cody bundles a native local symbol search engine called symf. Downloaded silently into your extension storage, symf builds a fast local index of symbol definitions across your local repository, pulling relevant symbol declarations into the prompt without calling an external server.

The Remote Tier: Zoekt Trigram Search and Code Graph

When Cody connects to a Sourcegraph Enterprise or Sourcegraph Cloud instance, it gains access to remote repositories. However, Cody does not execute heavy remote queries on every single character you type.

Instead, remote context serves as an asynchronous, cached knowledge layer:


2. What Happened to Vector Embeddings?

A common question 365Finds hears from engineering leaders is: “Where do embeddings fit into Cody’s autocomplete?”

In 2023, Sourcegraph Cody heavily promoted vector embeddings (using models like OpenAI's text-embedding-ada-002) stored in vector databases for codebase RAG. But in real-world software engineering, pure vector embeddings revealed glaring flaws:

Sourcegraph recognized these limitations and shifted Cody toward a hybrid search architecture. Vector embeddings are now largely relegated to high-level semantic chat queries. Autocomplete context is governed by deterministic lexical and structural tools: Tree-sitter, Zoekt trigram search, Jaccard heuristics, and SCIP code graphs. At 365Finds, we strongly endorse this architectural shift: compiler-grade symbols beat fuzzy vector geometry every time you need an exact function parameter.


3. How Cody Autocomplete Assembles a Prompt in Real Time

To see this system in motion, consider what happens in the 200 milliseconds after you pause typing:

[Keystroke Event]
       |
       v
1. Debounce & Hot Streak Evaluation
   (Determines if typing cadence warrants a completion request)
       |
       v
2. Tree-Sitter AST Intent Parsing
   (Identifies scope: e.g., calling a method on an imported client)
       |
       v
3. Candidate Retrieval Pipeline
   |-- Local: Open tabs ranked by Jaccard similarity score
   |-- Local: symf symbol lookup for referenced classes
   `-- Remote: Cached type definitions from indexed remote repos
       |
       v
4. Context Pruning & Budgeting
   (Trims context to fit strict prompt token limits, usually 1k-2k tokens)
       |
       v
5. FIM Prompt Dispatch to LLM
   (Sends: <PRE> code ... <CONTEXT> snippets ... <SUF> code ... <MID>)
       |
       v
6. Output Parsing & Multi-line AST Truncation
   (Tree-sitter inspects completion output; truncates runaway syntax)
       |
       v
[Inline Ghost Text Displayed in Editor]

Context Budgeting: Why Less Is More

Completions LLMs (such as DeepSeek-Coder-V2) can easily hallucinate or slow down if flooded with dozens of irrelevant files. Cody applies strict context budgeting:


4. How to Configure Local and Remote Indexing in Cody

Getting the best contextual suggestions out of Cody requires intentional setup across both your local editor and your remote Sourcegraph instance.

Step 1: Optimize Local IDE Settings

In VS Code or JetBrains, verify that autocomplete and local search mechanisms are enabled in your user or workspace settings.json:

{
  "cody.autocomplete.enabled": true,
  "cody.autocomplete.advanced.provider": "fireworks",
  "cody.autocomplete.advanced.model": "deepseek-coder-v2-lite"
}

Step 2: Connect Remote Repositories via Sourcegraph

To allow Cody to draw context from shared libraries, internal packages, and remote microservices:

  1. Connect your IDE extension to your organization’s Sourcegraph instance using your Sourcegraph URL and an authenticated Access Token.
  2. In the Sourcegraph instance web console, navigate to Site Admin > Repositories > Manage Repositories.
  3. Ensure your target repositories are cloned and status shows Indexed. Zoekt runs automatically in the background to build trigram indices.

Step 3: Configure Context Filters to Cut Multi-Repo Noise

If your organization has 500 repositories on Sourcegraph, allowing Cody to query all of them blindly degrades suggestion accuracy and increases response latency. Administrators should enforce Cody Context Filters in Site Configuration:

{
  "cody.contextFilters": {
    "include": [
      { "repoNamePattern": "^github\\.com\\/your-org\\/(core-api|shared-types|design-system|services\\/.*)" }
    ],
    "exclude": [
      { "repoNamePattern": ".*-deprecated$" },
      { "repoNamePattern": ".*\\/legacy-monolith\\/vendor\\/.*" },
      { "repoNamePattern": ".*-test-fixtures$" }
    ]
  }
}

5. 365Finds Assessment: Strengths, Tradeoffs, and Verdict

ComponentHow It Performs365Finds Take
Tree-sitter AST ParsingFlawless local syntax scoping; trims hallucinated bracketsThe unsung hero of Cody’s autocomplete quality
Jaccard Tab MatchingInstant token overlap scanning across open editor buffersExtremely fast; rewards developers who keep related files open
symf Local IndexerLow-overhead symbol search without server roundtripsReliable bridge between active buffers and local project files
Zoekt Trigram SearchMillisecond-level regex and keyword matching on remote instancesFar superior to pure vector databases for exact symbol retrieval
Vector EmbeddingsDe-emphasized for autocomplete; preserved for Chat RAGThe right architectural call; vectors are too slow for keystroke SLAs
Cross-Repo AutocompleteDependent on cached symbols and context filtersImpressive when configured tightly; noisy if left unrestricted

What 365Finds Recommends

Sourcegraph Cody’s context retrieval architecture is one of the most technically sound in the AI developer tools landscape. While competitors rushed to slap vector databases on top of general-purpose LLMs, Sourcegraph leveraged a decade of enterprise code search engineering: Zoekt trigram indexes, SCIP code graphs, and Tree-sitter ASTs.

However, don't expect remote repository indexing to act like an omniscient magic wand out of the box. Real-time autocomplete lives or dies on local latency. If your team wants pristine, context-rich completions across a multi-repo architecture, the formula is clear:

  1. Connect your extension to an active Sourcegraph instance with pre-indexed Zoekt repositories.
  2. Restrict repository scope using cody.contextFilters to eliminate legacy noise.
  3. Keep relevant schema, interface, and model tabs open in your IDE while coding.

By anchoring your workflow in structural code intelligence rather than fuzzy semantic hype, Sourcegraph Cody delivers completions that match what your codebase actually looks like.


References