How to use AI agents to understand, refactor, and evolve legacy and brownfield codebases safely.
Before modifying unfamiliar code, always explain first:
| Command | Use Case |
|---|---|
/explain on selection |
Understand what selected code does |
/explain #file |
Get overview of an entire file's responsibilities |
@workspace + question |
Explore architecture across the project |
/explain on error |
Understand a stack trace or build error |
Example prompt:
When refactoring brownfield code, pick the narrowest vertical slice through your system:
@workspace and LSP (find-references, type-hierarchy) to map every caller and dependencyEach phase gets a fresh AI context with only the artefacts from the previous phase. This prevents the agent from hallucinating based on stale conversation context.
Multi-file refactoring with test preservation. Three example prompts:
Service extraction:
Pattern migration:
Code modernisation:
How Dependabot + Copilot work together:
Tip: Combine Dependabot PRs with agent mode. If a dependency update breaks something, ask agent mode: "Fix the build failures caused by the upgrade to [library] v[X]. Check the migration guide at [URL]."
Before any refactoring, ensure your harness:
| Layer | What It Catches | How to Set Up |
|---|---|---|
| Compiler / type checker | Type errors, missing references | Already there โ just build |
| Unit tests | Logic errors, calculation drift | /tests to generate baseline coverage |
| E2E tests (Playwright) | Behavioural changes, broken flows | Agent mode: "Write Playwright tests for the [X] flow" |
| Linter / analyser | Style drift, code smells | Configure in CI pipeline |