Most AI assistants choke on legacy code. Hand a generic language model a 600-line function written in 2018, and it will confidently explain the syntax while completely missing the hidden architectural landmines. Ask it to write a unit test, and it invents mock libraries that do not exist in your repository or imports Jest methods into an old Mocha harness.
The failure is rarely the model's reasoning capacity. It is context starvation.
Legacy systems are webs of implicit state, cross-repository utility calls, and conventions decided six years ago by engineers who left the company three reorganizations back. At 365Finds, we look at developer tooling through a practical lens: does it save hours of reverse engineering, or does it add another layer of hallucinated cleanup? Sourcegraph Cody attacks the legacy problem differently from competitors like GitHub Copilot by anchoring its prompts to Sourcegraph’s Code Graph and multi-repository search infrastructure.
Here is exactly how Cody leverages full codebase context to decode legacy logic and construct unit tests that compile and run.
The Core Engine: Why Cody's Context Differs from Local LLMs
Standard IDE chat plugins look primarily at your active tab, recent open tabs, and a shallow local vector index. When dealing with legacy code, that local window is almost useless. The function you need to refactor might depend on an internal authorization module living in a separate repository or an unindexed configuration object three directories up.
Sourcegraph Cody connects directly to the Sourcegraph code intelligence backend. It pulls context through three layered mechanisms:
- Precise Code Intelligence & Code Graph: Rather than guessing symbol definitions based on text similarity, Cody uses Sourcegraph's compiler-level structural understanding (SCIP / LSIF). It traces exact definition-to-reference relationships across classes, interfaces, and methods.
- Universal Code Search: Sourcegraph indexes text, commit history, and symbols across dozens or thousands of repositories. When Cody searches for context, it runs hybrid search—combining semantic similarity with exact symbol queries.
- Intentional Scope Control (
@-mentions): Cody allows developers to manually pin context using@file,@symbol, or@codebase. Instead of trusting an opaque auto-retrieval pipeline to pick the right files, you can point Cody straight at the relevant legacy interfaces.
365Finds considers this architectural backbone the single deciding factor between Cody and single-repo assistants. If Cody only analyzed the active editor buffer, it would be another generic wrapper. Connected to a fully indexed Sourcegraph instance, it acts like a senior architect who has read every commit in your organization.
Step 1: Explaining Legacy Code Without Missing Side Effects
When you encounter an undocumented legacy module, the danger is rarely the raw syntax. The danger lies in hidden side effects, obsolete business logic, and unexpected external calls.
The Targeted Workflow
Instead of typing a vague prompt like "Explain this code," follow this structured query pattern in the Cody chat panel:
@codebase @legacy_payment_router.py
Explain how handle_recurring_billing processes delinquent accounts.
Trace all external service calls and identify any shared or mutable state modified outside this module.
What Cody Does Behind the Scenes
- Resolves Symbol Dependencies: Cody queries the Code Graph to find every caller of
handle_recurring_billingacross the codebase. - Identifies Upstream and Downstream Data Flows: If
legacy_payment_router.pycalls an internal microservice client defined in another repository, Cody fetches that client's signature and error models. - Flags Latent Dead Code and Workarounds: Cody can compare current invocation patterns with older code paths. If a conditional branch references a configuration parameter no longer present in any live config file, Cody highlights it as obsolete.
365Finds Field Note: Watch Out for Global Search Noise
Our main hesitation with unconstrained @codebase queries on massive enterprise repos is retrieval noise. If you ask Cody a broad conceptual question, it can pull irrelevant files that happen to share generic function names like process() or execute(). For tight legacy investigations, 365Finds strongly recommends pairing @codebase with at least one explicit @file or @symbol anchor.
Step 2: Generating Working Unit Tests for Untested Code
Writing tests for legacy code is usually an exercise in characterization testing: pinning down what the code currently does before refactoring it, without altering behavior.
When engineers ask standard AI tools to generate tests, they often receive idealized code that fails in CI. The AI assumes modern testing fixtures, creates incompatible mocks, or ignores required dependency injection containers.
How Cody Solves the Testing Context Gap
When you run Cody's built-in /test command or write a custom test prompt, Cody does not draft tests in a vacuum. It executes a retrieval step against your repository’s existing test suites:
- Framework Detection: It identifies whether your project standardizes on Pytest, Jest, Mocha, JUnit 5, or an internal wrapper.
- Fixture Reusability: It searches for existing mock factories, database seeders, and setup fixtures used by neighboring test files.
- Assertion Conventions: It adheres to existing assertion styles (e.g., Chai
expectvs. nodeassert).
Practical Procedure: Generating Characterization Tests
To generate robust regression tests for a brittle legacy module, execute this sequence:
- Highlight the Target Function: In your IDE (VS Code or JetBrains), select the legacy function.
- Feed Existing Test Reference: In the Cody prompt, use
@-mentionsto point to a high-quality existing test file in the same directory:/test @tests/unit/test_payment_helpers.py Generate characterization tests for handle_recurring_billing. Include edge cases for null currency fields, network timeouts from the billing gateway, and verify that the transaction log emitter is invoked exactly once. - Inspect Mocking Boundaries: Cody references
test_payment_helpers.pyto see how database clients and network calls are mocked across the team. It replicates those exact mock patterns rather than inventing arbitrary stubs.
Comparative Assessment: Where Cody Wins and Where It Stumbles
At 365Finds, we test developer products against tough enterprise trade-offs. Sourcegraph Cody is not an effortless plug-and-play tool for every team.
| Dimension | Sourcegraph Cody | Standard IDE AI (e.g. Baseline Copilot) |
|---|---|---|
| Multi-Repository Context | Native; indexes across all organizational repositories via Sourcegraph backend | Generally restricted to open tabs and local workspace folder |
| Legacy Dependency Tracing | High; powered by precise Code Graph (SCIP) definition/reference indices | Moderate to low; relies heavily on heuristic lexical search |
| Testing Pattern Alignment | Strong; inspects existing repo test files to replicate fixtures and mocking styles | Inconsistent; prone to generating incompatible modern test syntax |
| Infrastructure Overhead | Significant; requires an active Sourcegraph instance for full multi-repo power | Minimal; plug-in installation with SaaS authentication |
| Standalone Local Performance | Comparable to standard chat assistants without remote indexing | Fast, lightweight local file indexing |
If your team works in a clean, self-contained modern monorepo, Cody’s infrastructure advantage is less noticeable. But if your daily reality involves navigating a 10-year-old distributed microservices architecture where documentation exists only in Git blame history, 365Finds recommends Cody specifically because it bridges the chasm between isolated code files and whole-org architecture.
Setting Up Cody for Legacy Repositories
To get the full depth of codebase context on legacy systems, configure your environment properly:
- Connect to Sourcegraph Enterprise: Ensure your IDE extension is authenticated against your company's self-hosted or Cloud Sourcegraph instance, not merely running in disconnected local mode.
- Verify Repository Indexing: Confirm in your Sourcegraph admin console that the target repositories and their dependencies have completed code intelligence indexing (SCIP/LSIF).
- Configure Context Filters: If your legacy repository handles sensitive PII or regulated compliance data, use Cody Context Filters to restrict which directories or modules feed into remote LLM prompts.
Cody works best when treated as an interactive co-pilot rather than an autonomous rewriter. Use it to trace call graphs, draft baseline assertions, and pinpoint obscure side effects, then verify the generated suites against your existing test runners.