AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Engineering Teams Configure Sourcegraph Cody with Multi-Repository Context to Explain Legacy Code and Search Organizational Codebases

365Finds Editorial
Indexed 11,457 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

In large engineering organizations, software rarely lives within an isolated repository. Microservices communicate across distributed RPC interfaces, frontend web applications depend on versioned API contracts, and core business domains frequently rely on decades-old monolithic architectures. When developers attempt to navigate or modernize these environments using standard AI coding assistants, they run into a hard limitation: conventional tools only inspect the locally opened file or workspace folder. They lack visibility into shared libraries, downstream services, and historical implementations located in other repositories.

Sourcegraph Cody solves this problem by decoupling AI context from the local editor workspace. Backed by Sourcegraph's code intelligence platform, Cody can retrieve context across hundreds or thousands of repositories hosted on GitHub, GitLab, Bitbucket, or internal Git servers.

This guide details how engineering teams configure Sourcegraph Cody with multi-repository context, the administrative architecture required to index and govern organizational codebases, and how developers leverage this capability to unravel undocumented legacy systems and search across enterprise-scale repositories.


1. Architectural Foundations: How Multi-Repo Context Operates

Unlike AI assistants that rely solely on client-side retrieval or local folder embeddings, Cody retrieves multi-repository context through a centralized infrastructure:

┌─────────────────────────────────────────────────────────────┐
│                       Developer IDE                         │
│     (VS Code / JetBrains / Visual Studio / Cody Web)        │
│   - Context Chips: Current File + Pinned Repos (Up to 10)   │
│   - Granular @-Mentions (@repo, @dir, @file, @symbol)       │
└──────────────────────────────┬──────────────────────────────┘
                               │ HTTPS / Access Token
                               ▼
┌─────────────────────────────────────────────────────────────┐
│             Sourcegraph Enterprise Instance                 │
│                 (Cloud or Self-Hosted)                      │
│                                                             │
│  ┌─────────────────────────┐   ┌─────────────────────────┐  │
│  │    Search Engine        │   │       Code Graph        │  │
│  │   (Zoekt Trigram)       │   │  (SCIP Semantic Index)  │  │
│  └─────────────────────────┘   └─────────────────────────┘  │
│  ┌─────────────────────────┐   ┌─────────────────────────┐  │
│  │    Context Filters      │   │ Permissions & Auth Sync │  │
│  │   (Exclude Repos)       │   │   (GitHub/GitLab RBAC)  │  │
│  └─────────────────────────┘   └─────────────────────────┘  │
└──────────────────────────────┬──────────────────────────────┘
                               │ Prompt + Grounded Code Chunks
                               ▼
┌─────────────────────────────────────────────────────────────┐
│                 LLM Provider (Cody Gateway)                 │
│         (Claude 3.7 / 3.5 Sonnet, GPT-4o, etc.)             │
└─────────────────────────────────────────────────────────────┘
  1. Centralized Repository Indexing: Sourcegraph indexes all connected code hosts using Zoekt (a high-performance trigram search engine) and SCIP (Source Code Intelligence Protocol) indexers. This creates a global symbol graph covering definitions, call sites, and inheritance across every repository.
  2. Permission-Aware Retrieval: Cody respects repository permissions configured at the code host level. When a developer asks a question, Cody only queries and retrieves context from repositories that the developer's identity is authorized to access.
  3. Targeted Context Injection: Rather than passing entire remote repositories into an LLM prompt—which would quickly exceed token windows and degrade model attention—Cody uses Sourcegraph's Search API to extract precise symbol definitions, relevant code blocks, and interface declarations.

Multi-repository context is natively available for Cody Enterprise users (via Sourcegraph Cloud or self-hosted Sourcegraph Enterprise). Cody Free and Pro tiers operate primarily on single-repository local context.


2. Infrastructure & Administrator Configuration

Setting up multi-repository context begins on the Sourcegraph instance. Site administrators must ensure code hosts are synced, indexing is active, and Cody Enterprise is enabled.

Step 1: Connect Code Hosts and Enable Synchronization

In your Sourcegraph instance, navigate to Site Admin > Code Hosts (/site-admin/external-services) and configure connections to your version control systems (e.g., GitHub Enterprise, GitLab Self-Managed, Bitbucket Data Center).

Configure repository selection rules to ensure both modern microservices and legacy monoliths are included:

{
  "url": "https://github.com",
  "token": "ghp_yourEnterpriseSyncToken",
  "orgs": ["engineering-core", "legacy-platforms", "shared-libraries"]
}

Verify that background cloning and periodic synchronization workers complete without authentication errors.

Step 2: Configure Code Graph and Auto-Indexing

While keyword and Zoekt text search function immediately after cloning, explaining complex legacy logic requires semantic code navigation (finding references across repository boundaries).

  1. In Site Admin > Code Navigation, ensure auto-indexing is enabled.
  2. For mission-critical repositories using languages such as Go, TypeScript/JavaScript, Java, Python, or C++, generate and upload SCIP indexes through CI/CD pipelines (e.g., using GitHub Actions or GitLab CI) using the corresponding indexer (such as scip-typescript, scip-java, or scip-python).
  3. These semantic indexes allow Cody to trace callers and implementations across separate repositories without guessing.

Step 3: Enable Cody and Model Configuration

Go to Site Admin > Site Configuration (/site-admin/configuration) and enable Cody:

{
  "cody.enabled": true,
  "completions": {
    "provider": "sourcegraph"
  }
}

Select an LLM model optimized for large context reasoning (such as Anthropic Claude 3.5 Sonnet or Claude 3.7 Sonnet via Cody Gateway, or Azure OpenAI GPT-4o). Ensure that cody.restrictUsersFeatureFlag is not blocking team access.

Step 4: Configure Context Filters for Sensitive Repositories

Engineering organizations often maintain security repositories, PCI-compliant vaults, or proprietary algorithm silos that should not be indexed into chat retrieval.

Use Cody's Context Filters (cody.contextFilters) to exclude specific repositories from being read by Cody in chat and completions:

{
  "cody.contextFilters": {
    "exclude": [
      { "repo": "github.com/company/pci-vault-service" },
      { "repo": "github.com/company/compliance-secrets-.*" }
    ]
  }
}

3. Developer Client Configuration in VS Code, JetBrains, and Web

Once the instance is operational, developers configure their local IDEs to activate multi-repository capabilities.

Step 1: Connecting the IDE Extension

  1. Install the official Cody: AI Coding Assistant with Autocomplete & Chat extension in VS Code, JetBrains (IntelliJ, PyCharm, GoLand, WebStorm), or Visual Studio.
  2. Click the Cody icon in the activity bar and select Sign In with Sourcegraph Enterprise.
  3. Enter your organization's Sourcegraph instance URL:
    https://sourcegraph.internal.company.com
    
  4. Complete the browser-based single sign-on (SSO) flow or paste a personal access token generated from your Sourcegraph account settings.

Step 2: Mapping Local Repositories (cody.codebase)

By default, Cody detects the Git remote origin of your local folder and matches it with the repository slug on your Sourcegraph instance.

If your local clone directory name differs, or if you are working within a submodule, verify or explicitly declare the codebase identifier in your workspace settings (.vscode/settings.json):

{
  "cody.codebase": "github.com/organization/core-payment-service"
}

Step 3: Managing Multi-Repo Context in Chat

When opening a new Cody Chat window, Cody automatically attaches default context chips:

To pull in context from other organizational repositories:

  1. The Context Management Bar: Above the chat input, click the context chips. You can add up to 10 remote repositories directly to the active session. Once pinned, every question you ask automatically leverages Sourcegraph search across those designated codebases.
  2. Explicit @-Mentions:
    • @repo/organization/legacy-billing-monolith: Pulls context from the entire legacy billing repository.
    • @dir/organization/auth-service/pkg/middleware: Targets a specific module or directory within another repository.
    • @file/organization/proto-contracts/v2/payment.proto: Pulls in exact schema definitions without checking out the repository locally.
    • @symbol: Mentions a specific class, interface, or struct known to exist across your codebase.
  3. Cody Web Application: For developers who need to explore architecture across hundreds of repositories without opening an IDE, open your Sourcegraph web portal (https://sourcegraph.company.com), click the Cody icon in the navigation bar, and run queries against all indexed enterprise repositories.

4. Practical Playbook: Explaining Legacy Code Across Multiple Repositories

Legacy systems often suffer from absent original authors, sparse or obsolete documentation, and logic fragmented across microservices or monolithic batch scripts. Here is how engineering teams use Cody with multi-repo context to understand and modernize legacy architectures.

Scenario A: Tracing an End-to-End Distributed Request

Suppose you are investigating why a legacy billing system occasionally drops charge notifications originating from a modern checkout microservice.

In your editor, with the modern checkout-service open:

Developer Query: @checkout-service @legacy-billing-monolith @event-bus-contracts "Trace how an OrderSubmittedEvent emitted by the Checkout service is consumed by the legacy billing monolith. What database tables are mutated, and under what conditions is an account balance deduction skipped?"

What Cody Does Behind the Scenes:

  1. Inspects the event payload defined in @event-bus-contracts.
  2. Searches @legacy-billing-monolith for event consumer listeners or queue workers subscribing to the event topic.
  3. Identifies the legacy transactional service classes and traces the SQL statements or stored procedure calls modifying account balances.
  4. Identifies legacy validation rules (such as hardcoded legacy partner IDs or outdated currency conversion fallbacks) that cause skipped deductions.

Scenario B: Deciphering Undocumented Business Logic and Algorithms

Legacy code often contains complex mathematical routines or status-checking state machines without explanatory comments.

Developer Query: @core-monolith/src/main/resources/rules/pricing_engine_v1.rb @pricing-integration-tests "Explain the state machine and edge cases handled in calculate_tiered_rebate. Cross-reference this with the historical integration tests in @pricing-integration-tests to explain why negative adjustments are applied when tier thresholds cross quarterly boundaries."

Cody synthesizes the source code alongside the assertion patterns found in historical test suites, translating convoluted branching logic into structured domain explanations.

Scenario C: Pre-Migration & Deprecation Impact Analysis

Before decommissioning a legacy gRPC endpoint or internal database column:

Developer Query: @user-profile-service @notification-service @reporting-worker "We plan to deprecate GetUserPreferencesV1 in @user-profile-service. Which downstream services in our pinned context call this endpoint, which fields do they actively parse, and what changes are required to migrate them to GetUserPreferencesV2?"

Cody cross-references caller definitions, extracts the exact schema usage from client stubs in the consumer repositories, and produces a step-by-step migration diff for each service.


5. Searching Organizational Codebases with Cody

Standard codebase search requires knowing exact function names, file paths, or regex syntax. Cody combines natural language understanding with Sourcegraph's search engine to answer organizational discovery queries.

Finding Canonical Implementations

When engineering teams grow, different squads often reinvent the wheel—writing duplicate caching layers, HTTP clients, or token refresh logic.

Developer Query: "How do our Go microservices implement distributed rate limiting with Redis? Show me the most widely used internal package or reference implementation across the organization."

Cody scans organizational repositories, evaluates imported rate-limiting utilities, identifies the standard internal library (e.g., pkg/ratelimit), and provides code snippets showing idiomatic usage according to company standards.

Auditing Security Patterns and Outdated Practices

When modernizing cryptography or addressing vulnerabilities across dozens of services:

Developer Query: @payment-service @auth-service @mobile-api-gateway "How is JWT token validation configured across these repositories? Are any services still accepting unverified claims or deprecated signing algorithms like RS256 without key rotation checks?"

Cody parses the middleware setup in each repository and produces a consolidated security summary highlighting inconsistencies between services.


6. Best Practices, Pitfalls, and Operational Guardrails

To ensure optimal performance and accuracy when using multi-repo context, teams should adopt several operational habits:

Best PracticeRationale
Pin 2–5 Related Repositories per SessionWhile Cody supports up to 10 repositories in a chat session, pinning too many unrelated codebases introduces noise and consumes context window space with peripheral snippets.
Use Specific @dir and @file Mentions for Core ContractsExplicitly mentioning interface definition files (e.g., .proto, OpenAPI YAML, GraphQL schemas) ensures the model focuses on the authoritative contract rather than incidental implementation details.
Maintain Regular Code Graph (SCIP) IndexingZoekt text search identifies literal keywords, but SCIP indexing provides precise cross-repository symbol navigation. Integrate SCIP index generation into CI jobs for core shared packages.
Verify Context Chips Before SubmittingCheck the context chips displayed above the chat input to confirm that irrelevant repositories or files are removed prior to asking architecture-level questions.
Pair Cody with Sourcegraph Batch ChangesUse Cody chat to understand legacy architecture and plan changes, then use Sourcegraph Batch Changes to execute and test multi-repository refactors via automated declarative pull requests.

Conclusion

Configuring Sourcegraph Cody with multi-repository context transforms AI from a local autocomplete assistant into an enterprise-wide code intelligence partner. By bridging version control hosts, precise semantic code graphs, and enterprise access controls, Cody enables engineering teams to understand intricate legacy dependencies, execute safe cross-service migrations, and search organizational codebases with confidence.


References