AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Sourcegraph Cody Indexes and Retrieves Context Across Multi-Repository Enterprise Codebases

차재현 · 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

Most AI coding assistants crumble the moment your architecture outgrows a single repository. If your application frontend consumes an internal API defined in a secondary service, which in turn depends on shared data models in a core library repository, standard local-workspace tools hallucinate signatures, invent non-existent endpoints, or shrug. At 365Finds, we consider cross-repository context the single defining test of whether an AI tool belongs in enterprise software development.

Sourcegraph Cody takes a fundamentally different engineering path. Instead of forcing your local IDE to build clumsy ad-hoc vector dumps or relying strictly on open editor tabs, Cody offloads codebase indexing and context retrieval to an enterprise backend. By combining Sourcegraph’s Zoekt trigram search engine, SCIP-based code graphs, hybrid semantic embeddings, and granular context filtering, Cody turns distributed enterprise repositories into a navigable, permission-aware context graph.

Here is an architectural breakdown of how Sourcegraph Cody indexes multi-repository codebases, how its context retrieval pipeline works during active queries, and how engineering teams should configure it for deterministic precision.


1. The Multi-Repo Problem: Why Local Vector RAG Fails

Standard AI tools use localized Retrieval-Augmented Generation (RAG). They slice open files into chunks, compute vector embeddings, store them in a temporary local vector cache, and perform nearest-neighbor searches against user prompts.

In enterprise multi-repo architectures, this model breaks down immediately:

At 365Finds, our research emphasizes that enterprise code search must be structural and deterministic, not merely probabilistic. This is where Sourcegraph’s backend infrastructure changes the calculation.


2. The Enterprise Indexing Architecture

Sourcegraph Cody does not index multi-repository environments from the developer's client. Instead, it relies on the centralized Sourcegraph Enterprise instance (self-hosted or cloud-managed) connected directly to your organization’s code hosts (GitHub, GitLab, Bitbucket, or Perforce).

The backend executes a three-part indexing pipeline across every synced repository:

[Code Hosts: GitHub / GitLab / Bitbucket]
                    │
                    ▼
       Sourcegraph Backend Sync
                    │
      ┌─────────────┼─────────────┐
      ▼             ▼             ▼
 [Zoekt Engine]  [SCIP Graph]  [Hybrid Embeddings]
  Trigram Text    Definitions    Dense Vectors
  & Regex Search  & References   Semantic Intent

Zoekt: High-Throughput Trigram Indexing

Zoekt is Sourcegraph's open-source, trigram-based search engine designed specifically for source code. Zoekt breaks every file down into 3-character n-grams (trigrams) and builds an inverted index over the code text.

SCIP: Precise Code Graph Intelligence

Keyword search tells you where text appears; it does not tell you what the code does. Sourcegraph uses SCIP (Sourcegraph Code Intelligence Protocol), a language-agnostic code graph protocol that succeeded LSIF.

Hybrid Vector Embeddings

To complement Zoekt and SCIP, Sourcegraph supports chunk-based vector embeddings. Code is split along logical boundaries (functions, classes, structural blocks) and vectorized. When a developer asks a high-level conceptual question—such as "how do we handle dead-letter queues in our ingestion pipeline?"—semantic embeddings surface the relevant code chunks even if the exact words "dead-letter" are absent from the function name.


3. The Retrieval Pipeline: How Cody Pulls Context at Runtime

When a developer prompts Cody in their IDE (VS Code, JetBrains) or in Cody Web, the system triggers a multi-stage context retrieval pipeline.

       [Developer Prompt in IDE]
                    │
                    ▼
     [Intent & Query Expansion]
     (Extract symbols, paths, topics)
                    │
     ┌──────────────┴──────────────┐
     ▼                             ▼
[Local Workspace Context]    [Remote Multi-Repo Context]
- Active buffer & selection  - Sourcegraph Search API (Zoekt)
- Recent file tabs           - SCIP definition & reference graphs
- Local Git diffs            - Vector embeddings
     │                             │
     └──────────────┬──────────────┘
                    ▼
       [cody.contextFilters & RBAC]
         Permission & Policy Check
                    │
                    ▼
    [Re-ranking & Token Budgeting]
      (Deduplication & Concision)
                    │
                    ▼
          [Augmented LLM Prompt]

Step 1: Query Intent Parsing & Expansion

Cody first parses the user prompt. A lightweight analyzer extracts symbol candidates, file path hints, and natural language concepts. If the prompt says:

"How does payment-service validate tokens generated by auth-service?"

Cody splits this into multiple retrieval requests:

  1. Exact symbol lookups for token validation functions.
  2. File path filters targeting payment-service and auth-service.
  3. A semantic search query covering token validation mechanisms.

Step 2: Multi-Repository Traversal

Cody concurrently queries two context tiers:

  1. Local Context: The developer’s open file, selected code snippet, recently viewed files, and local Git diffs.
  2. Remote Multi-Repo Context: The Sourcegraph Search API queries the indexed enterprise repositories using Zoekt and the code graph to locate definitions, usages, and matching documentation.

Step 3: Explicit Scoping via @-mentions

While Cody can automatically detect context, 365Finds strongly advises developers working across microservices to guide retrieval explicitly using @-mentions.

This cuts retrieval latency and prevents unrelated repositories from polluting the context window.

Step 4: Access Control and Context Filtering

Enterprise security is non-negotiable. Before any remote snippet enters the LLM prompt, Cody enforces two layers of validation:

  1. Code Host RBAC Synchronization: Sourcegraph continuously mirrors access permissions from GitHub/GitLab. If a developer does not have read access to a proprietary repository on GitHub, Cody refuses to pull context from it.
  2. Context Filters (cody.contextFilters): Administrative rules that programmatically restrict which repositories Cody can read (explained below).

Step 5: Ranking, Pruning, and Token Budgeting

LLM context windows are precious. Cody's ranking engine evaluates candidate snippets using relevance scoring:

The context assembler trims excessive boilerplate, collapses duplicate definitions, and injects only the essential code slices into the prompt sent to the LLM (Claude, GPT, or Gemini).


4. How to Configure Multi-Repo Context: Step-by-Step

To achieve reliable cross-repository context, enterprise teams must configure both backend indexing and administrative governance.

Step 1: Ensure Full Code Host Synchronization and Zoekt Indexing

In the Sourcegraph Site Admin dashboard, verify that all participating repositories are actively mirrored and indexed:

  1. Navigate to Site Admin > Repositories.
  2. Confirm the code host connection (e.g., GitHub Enterprise or GitLab Self-Managed) has repository discovery enabled.
  3. Check the Search Indexing status. Every target repository must show Indexed under Zoekt status. Repositories with pending or disabled indexing fall back to unindexed search, which severely degrades Cody's cross-repo retrieval speed and depth.

Step 2: Configure cody.contextFilters for Governance and Noise Reduction

We consider cody.contextFilters a mandatory configuration, not an optional preference. Without context filters, Cody may scan internal utility mirrors, archive forks, or compliance-restricted repositories.

Site administrators configure this in the Sourcegraph Site Configuration JSON (Site Admin > Configuration):

{
  "cody.contextFilters": {
    "include": [
      {
        "repoNamePattern": "^github\\.com\\/mycompany\\/(services|libraries|apis)\\/.+"
      }
    ],
    "exclude": [
      {
        "repoNamePattern": ".*-deprecated$"
      },
      {
        "repoNamePattern": "^github\\.com\\/mycompany\\/security-vault"
      },
      {
        "repoNamePattern": ".*-vendor$"
      }
    ]
  }
}

Step 3: Connect Client IDEs to the Enterprise Endpoint

Developers must connect their IDE extension directly to the enterprise instance rather than using individual Cody Free/Pro accounts:

  1. Open Cody settings in VS Code or JetBrains.
  2. Under Enterprise Instance URL, enter https://sourcegraph.internal.mycompany.com.
  3. Authenticate via your enterprise SSO or User Access Token.
  4. Verify in the Cody chat status bar that the active enterprise instance and repository context provider are recognized.

Step 4: Train Developers on Cross-Repo Chat Patterns

Cross-repo queries require conversational intent discipline. Contrast these two queries:

The second query allows Cody to bypass speculative multi-repo scanning and pull the exact interface definitions directly into the prompt.


5. 365Finds Institutional Evaluation & Recommendations

At 365Finds, we evaluate developer tooling based on real-world engineering trade-offs, not marketing claims. Here is our assessment of Sourcegraph Cody’s multi-repo indexing architecture:

Feature / DimensionSourcegraph Cody EnterpriseTraditional Local AI Assistants
Search EngineTrigram Zoekt + SCIP code graphLocal token-frequency or basic vector cache
Multi-Repo BreadthHundreds of remote repositories concurrentlySingle open workspace folder or active tab
Cross-Repo ReferencesCompiler-grade deterministic definitions via SCIPProbabilistic guesses based on name similarity
Governance & SecuritySite-wide regex context filters + Code Host RBACManual .gitignore or local file exclusion
Infrastructure OverheadHigh (Requires dedicated Sourcegraph instance)Zero (Runs entirely on client machine)

When We Strongly Recommend Cody

If your engineering organization operates across dozens of microservices, uses centralized API schema repos, or maintains shared internal SDKs, Sourcegraph Cody is arguably the most coherent enterprise coding assistant on the market. Its ability to anchor LLM responses in real code graphs prevents the subtle API hallucinations that plague lighter tools.

What to Watch Out For

  1. Infrastructure Cost: Sourcegraph Enterprise is an enterprise-grade platform. Running Zoekt and repository synchronization across thousands of repositories requires substantial compute, RAM, and SSD storage.
  2. Context Latency on Broad Queries: Asking completely unconstrained questions across hundreds of un-scoped repositories will introduce noticeable retrieval latency before the LLM begins streaming its response.
  3. The Necessity of Scoping Hygiene: Teams that rely entirely on passive retrieval will encounter occasional context poisoning. To extract the highest value from Cody, development leads must educate teams to use @repo and @file scoping.

Sourcegraph Cody succeeds in multi-repository enterprise environments because it does not treat code search as a secondary feature of an LLM. It treats the LLM as an interface over a mature, deterministic code intelligence engine.


References