AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Sourcegraph Cody Indexes and Queries Enterprise Codebases Without Leaking Data

Ong Lay Hoon · 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

Enterprise engineering leads face a stubborn paradox when evaluating AI coding assistants: large language models deliver remarkable productivity gains, yet the moment an assistant touches proprietary code, corporate security alarms start ringing. How can an AI assistant answer questions across five hundred microservices or a ninety-gigabyte monorepo without exposing confidential trade secrets to public training pools or unauthorized colleagues?

At 365Finds, we evaluate developer infrastructure through a pragmatic lens. Many AI assistants treat codebase intelligence as an afterthought—slapping basic vector embeddings onto recent files and praying the LLM guesses correctly. Sourcegraph Cody approaches the challenge from the opposite direction. Sourcegraph spent over a decade perfecting large-scale enterprise code search before generative AI existed. By mounting Cody directly on top of its distributed search and code intelligence engine, Sourcegraph delivers deep multi-repository context while enforcing rigorous enterprise data boundaries.

Here is how Sourcegraph Cody indexes massive codebases, assembles cross-repository context, and ensures proprietary code never leaks.


1. The Scaling Bottleneck: Why Pure Embeddings Fail on Enterprise Code

Standard AI assistants rely heavily on naive Retrieval-Augmented Generation (RAG). They slice code into arbitrary text chunks, convert them into vector embeddings, and run cosine similarity matches when a developer types a prompt.

On large corporate codebases, this pure-vector approach collapses quickly:

Sourcegraph avoids this pitfall by refusing to treat code merely as raw text. Instead of relying solely on vector embeddings, Cody leverages Sourcegraph’s deterministic enterprise intelligence architecture.


2. The Indexing Engine: Zoekt Trigrams, SCIP, and the Code Graph

When Sourcegraph connects to your code hosts—whether GitHub Enterprise, GitLab Self-Managed, or Bitbucket Data Center—it builds an enterprise-grade structural index designed to support sub-second querying across hundreds of gigabytes.

Trigram Indexing with Zoekt

At the foundation of Sourcegraph’s search tier sits Zoekt, an open-source, highly optimized trigram-based search engine written in Go. Zoekt breaks code down into three-character sequences (trigrams), building an inverted index of symbols, variable names, syntax tokens, and file paths. Zoekt allows Cody to execute regex and exact-keyword queries across tens of thousands of repositories in milliseconds.

Precise Code Intelligence via SCIP

For structural understanding, Sourcegraph uses the Source Code Integration Protocol (SCIP). Unlike heuristic parsers, SCIP indexers plug directly into language compilers and build systems (including Go, TypeScript, Java, C++, and Python).

SCIP constructs a deterministic code graph:


3. The Query Pipeline: How Cody Gathers Context

When an engineer opens their IDE (VS Code or JetBrains) and asks Cody a complex architectural question—such as "How do our internal payment services validate OAuth tokens against the central auth cluster?"—Cody does not blindly ship the entire codebase to an external API.

Instead, Cody runs a multi-layered context retrieval pipeline:

Developer Prompt in IDE
        │
        ▼
Intent Detection & Query Rewriting
        │
        ├────────────────────────────────────────────────┐
        ▼                                                ▼
Local Editor Context                        Remote Enterprise Context
- Active file & selection                   - Trigram search (Zoekt)
- Cursor position & recent edits            - Code graph navigation (SCIP)
- Open tabs & local diagnostics             - Vector embeddings (hybrid fallback)
        │                                                │
        └───────────────────────┬────────────────────────┘
                                ▼
                   Context Filter Evaluation
                   - Repo permission check (RBAC)
                   - cody.contextFilters (Allow/Deny)
                                │
                                ▼
                   Re-Ranking & Token Budgeting
                   - Deduplication & relevance score
                   - Strict token window packing
                                │
                                ▼
                   Augmented Prompt Construction
                                │
                                ▼
                   Inference (Zero-Retention LLM)
  1. Intent Analysis & Query Expansion: Cody inspects the query for symbols, function names, and structural clues, decomposing the prompt into precise search terms.
  2. Local Context Gathering: The IDE extension reads immediate context—the active file, visible lines, cursor position, recent diffs, and compiler diagnostics.
  3. Remote Multi-Repo Search: Cody queries the central Sourcegraph instance. Zoekt retrieves candidate text snippets across authorized services, while the SCIP code graph traverses dependency trees to pull imported type definitions.
  4. Explicit Mentions (@-mentions & OpenCtx): Developers can explicitly steer context by using @ syntax to reference specific files, symbols, repositories, or external documentation platforms. Through OpenCtx, Cody can also ingest live context from Notion, Jira, or internal documentation servers.
  5. Re-Ranking and Truncation: Cody ranks candidate snippets by architectural proximity and relevancy, discarding low-signal boilerplate to assemble a compact reference payload that fits within the target LLM’s token budget.

4. How Sourcegraph Cody Prevents Proprietary Code Leaks

Context retrieval is only half the battle. Enterprise CISOs need absolute assurance that proprietary intellectual property, customer PII, and credentials are never stored, leaked, or absorbed into public models.

Sourcegraph enforces four distinct operational boundaries:

Boundary 1: Zero-Retention and Non-Training Guarantees

For Cody Enterprise deployments, Sourcegraph maintains explicit, legally binding commercial agreements with foundation model providers (such as Anthropic and OpenAI):

Boundary 2: Repository Permission Enforcement (RBAC)

Cody does not bypass corporate access controls. When a developer queries Cody, all remote context searches inherit the user's existing repository permissions synced from the underlying code host (GitHub, GitLab, Okta SSO/SCIM). If an engineer does not have read access to the payments-core repository, Cody will never retrieve or present code from payments-core in that engineer’s IDE.

Boundary 3: Administrative Context Filters (cody.contextFilters)

Enterprises can implement server-level guardrails using RE2 regular expression filters. Administrators define explicit inclusion and exclusion rules within the Sourcegraph site configuration:

"cody.contextFilters": {
  "include": [
    {
      "repoNamePattern": "^github\\.com\\/acmecorp\\/.+"
    }
  ],
  "exclude": [
    {
      "repoNamePattern": "^github\\.com\\/acmecorp\\/(security-vault|billing-secrets|pki)$"
    }
  ]
}

When a repository matches an exclusion filter, Cody’s retrieval pipeline completely excludes it from context assembly. Even if an authorized developer explicitly asks Cody about code inside security-vault, Cody is prevented from extracting snippets or forwarding them to the LLM.

Boundary 4: Deployment Isolation and BYOK (Bring Your Own Key)

For organizations operating in tightly regulated sectors, Sourcegraph provides complete deployment isolation:


5. Architectural Comparison: Cody vs. Single-Repo AI Assistants

Architectural DimensionGeneric Coding AssistantsSourcegraph Cody Enterprise
Primary Context SourceActive file, open editor tabs, local Git historyLocal editor state combined with distributed multi-repo search
Indexing TechnologyBasic vector embeddings (naive chunking)Hybrid: Zoekt trigram full-text search, SCIP code graphs, vector retrieval
Enterprise Multi-Repo ScalePoor; struggles beyond a single open workspaceProven on 90GB+ monorepos and hundreds of thousands of repositories
Permission RespectClient-side only; no centralized repo RBACCentralized permission synchronization from GitHub/GitLab/SSO
Administrative Code MaskingLimited client .ignore filesEnforced server-side cody.contextFilters (Regex allow/deny rules)
Data Training PolicyVaries by tier; consumer tiers may log dataStrict commercial zero-retention and zero-training guarantees
Deployment TopologyMulti-tenant SaaS onlySelf-hosted VPC, single-tenant cloud, or private Bedrock/Azure OpenAI BYOK

6. The 365Finds Verdict: Practical Trade-offs

365Finds views Sourcegraph Cody as an exceptionally engineered enterprise solution, but adopting it is an infrastructural commitment, not an impulsive consumer upgrade.

What We Admire

The Operational Caveats

For organizations managing sprawling microservice architectures or massive monorepos, Sourcegraph Cody offers one of the most mature, security-conscious AI coding platforms on the market today.


References