Understand a legacy codebase with Claude Code before you change it
From the work/ 12 min read
Before you change a legacy codebase, have Claude Code read it in plan mode and build a four-layer map with evidence, saved in ARCHITECTURE.md.
- AI
- Claude Code
In this article (8)
To understand a legacy codebase with Claude Code, don't ask for changes yet. Open it in plan mode, which reads and explores without editing, and ask for a map in four layers: folders, entry points and data, dependencies, and risk zones, each fact tied to the file behind it. Save the map in ARCHITECTURE.md before the first change.
Below are the commands to start, the five exact prompts, how to save the map without bloating your CLAUDE.md, a Node script that checks the map doesn't cite files that don't exist, and how to pick the first change.
Don't change anything yet: read the legacy codebase in plan mode
A codebase you didn't write holds decisions you can't see: a cron job nobody documented, a file that looks dead but is imported by a deploy script, a payment function with no tests. If you ask an agent for a change before you know that, the agent doesn't know it either, and you end up reviewing a diff you can't judge.
So the first session only reads. The modes table in the permission modes docs lists plan as the mode for exactly this: exploring a codebase before changing it. In plan mode Claude reads files, runs shell commands to explore and writes a plan, but doesn't edit your source; edits stay blocked until you approve the plan. The approval flow is covered in Claude Code plan mode; here it's a reading tool.
cd path/to/repo
git status
git switch -c docs/architecture-map
claude --permission-mode plan
cdto the project root: the docs' recipe for a new project starts there, and from the root Claude Code loads the project'sCLAUDE.mdif there is one.git statusshould come back clean, so anything that changes afterwards came from the session.git switch -copens a branch for the map. The one file this session writes lands in its own commit; the full workflow is in a git workflow for AI agents.claude --permission-mode planstarts the session in plan mode. If you're already in a session,Shift+Tabcycles modes until the status bar reads⏸ plan mode on.
Two details from the docs matter in old code. Read-only commands (ls, cat, grep, find, wc and the read-only forms of git) run without a prompt; other commands go through the classifier or ask for approval. And content searches respect .gitignore, but if the repo has checked-in generated code or a vendored library, block reads of it with Read deny rules, as the large codebases guide shows. The rule syntax is in Claude Code permissions in settings.json.
The map in four layers
"Explain this codebase" gets you a friendly summary you can't act on. A layered map forces specific answers, in an order that goes from safe to sensitive: first what is there, then where work flows, then what it depends on, and last where it hurts to touch.
| Layer | What it answers | Where Claude looks | What you write down |
|---|---|---|---|
| 1. Folders | What each part is and how it runs | Folder tree, manifest, scripts, Dockerfile, CI | One line per folder; the install, run, test and build commands |
| 2. Entry points and data | Where work comes in and where it ends | Routes, webhooks, cron, queues, schema and migrations | Entry points with file and line; one flow traced end to end |
| 3. Dependencies | What it relies on, and what is stale or unused | Manifest, lockfile, imports, environment variables (names only) | Framework and runtime versions; critical libraries; external services |
| 4. Risk zones | Where a change can break something expensive | Git history, tests, file size, TODO and FIXME | A file, signal, evidence, risk table; questions for the team |
Scroll the figure sideways to see all of it
The order matters for a practical reason: each layer builds on the one before. You can't trace a flow (layer 2) without knowing which folders are hand-written and which are generated (layer 1), and you can't judge a risk (layer 4) without knowing which files touch money or data (layers 2 and 3). Ask for one layer per message, read the answer and correct it before moving on.
The exact prompts for Claude Code
The "Understand new codebases" section of common workflows starts broad, with "give me an overview of this codebase", then narrows to data models and to tracing one flow end to end. These prompts do the same with one more demand: every fact comes with its file, and "unconfirmed" when there's no proof.
1 · Folders
I'm inheriting this repository and I won't change anything yet. Give me layer 1
of the map: what each top-level folder holds, in one line; which parts are
hand-written, generated, vendored or config; and the commands to install, run,
test and build, taken from the files. Cite the file for every fact. If you
can't confirm something by reading, write "unconfirmed".
2 · Entry points and data
Layer 2: list the system's entry points (HTTP routes, webhooks, cron, queues,
CLI) with file:line. Trace the most important flow from the entry point to
where it is stored or sent, step by step. Tell me where the schema and the
migrations live.
3 · Dependencies
Layer 3: from the manifest and the lockfile, give me the framework and runtime
with versions, the libraries that touch money, auth or data, and the ones that
look unused (check with grep before you say so). List external services and
the environment variables the code reads: names only, never values.
4 · Risk zones
Layer 4: run
git log --since="12 months ago" --format= --name-only | sort | uniq -c | sort -rn | head -20
and cross those files with the ones without tests, the longest ones, the ones
that touch payments, auth or data, and the ones with TODO or FIXME. Give me a
table: file, signal, evidence, risk (high, medium, low). End with the
questions only someone on the team can answer.
5 · The plan
Write as your plan the content of docs/ARCHITECTURE.md with the four layers,
every fact with its file, and an open questions section. Don't propose code
changes.
- Folders. "I won't change anything yet" states the intent even though the mode already enforces it. Separating hand-written from generated code keeps the rest of the map from resting on files nobody edits. The commands come from the files (manifest, Makefile, CI), not from what the model assumes.
- Entry points and data.
file:lineturns every claim into something you can open. Tracing one whole flow teaches more than listing every flow halfway. - Dependencies. "Check with grep" avoids the classic mistake of calling a library unused when it's loaded through config. "Names only, never values" keeps secrets out of the conversation.
- Risk zones. The command counts how many times each file changed in the last year. We ran it on a real repository with Git Bash.
git logis in the read-only set;sortanduniqaren't on the list the docs give, so depending on your mode you may get a prompt: they only read, approve it. PowerShell has nouniq; run that step in Git Bash or WSL. - The plan. In plan mode Claude doesn't edit your source, but it does write a plan. Asking for the plan to be the map's content makes that file the only pending edit.
To hand it a specific file, use @: @package.json includes the content when it fits the read limit (25,000 tokens by default; a text file over 256KB isn't included), and @src/ shows the folder listing, not its contents. In a large codebase, the docs suggest delegating exploration to a subagent so only the findings come back.
Save it in an architecture file
When the plan holds up, approve it with "Yes, manually approve edits": Claude leaves plan mode and asks you to confirm each edit, and the only one should be docs/ARCHITECTURE.md. If you see another, reject it.
Scroll the figure sideways to see all of it
Why a separate file and not CLAUDE.md? The best practices page lists "describe your architecture and file layout in CLAUDE.md" under advice you can stop following, because Claude reads the repo itself. And per the memory docs, an @docs/ARCHITECTURE.md inside CLAUDE.md loads in every session: imports don't reduce context. The map is for you, for the next person and for the tasks that need it: reference it with @docs/ARCHITECTURE.md when a change touches a risk zone. If you want CLAUDE.md to name it, put the path in backticks, which isn't imported.
For CLAUDE.md itself, /init generates a first version with build commands, test instructions and conventions; if one exists, it suggests improvements instead of overwriting it. Run it after the map and trim it: what stays and what moves to skills or hooks is in a short CLAUDE.md with skills and hooks.
A map written by a model can cite a file that doesn't exist. This script catches that: it finds every path in backticks and checks that it's in the repo.
// check-map.mjs: every file path the map cites must exist in the repo.
import { readFileSync, existsSync } from "node:fs";
const map = process.argv[2] ?? "docs/ARCHITECTURE.md";
const lines = readFileSync(map, "utf8").split(/\r?\n/);
const EXT = /\.(json|md|ts|tsx|js|jsx|mjs|cjs|py|rb|go|php|sql|ya?ml|toml|prisma|liquid|css|html|sh)$/i;
const isPath = (s) =>
!/\s|\*|^\/|^\$|^[a-z]+:/i.test(s) && (s.includes("/") || s.startsWith(".") || EXT.test(s));
let checked = 0;
const missing = [];
lines.forEach((line, i) => {
for (const [, span] of line.matchAll(/`([^`]+)`/g)) {
const path = span.replace(/#.*$/, "").replace(/:\d+(-\d+)?$/, "");
if (!isPath(path)) continue;
checked++;
if (!existsSync(path)) missing.push(`line ${i + 1}: ${path}`);
}
});
for (const m of missing) console.log(`MISSING ${m}`);
console.log(`${missing.length ? "FAIL" : "OK"}: ${checked} paths checked, ${missing.length} missing`);
process.exit(missing.length ? 1 : 0);
- It reads the map you pass in, or
docs/ARCHITECTURE.mdby default, and splits it into lines (CRLF line endings from Windows work too). EXTandisPathdecide what counts as a path: no spaces or wildcards, and a slash, a leading dot or a code file extension. HTTP routes like/api/orders, variables like$DATABASE_URL,node:fs, commands and globs are skipped.- For each backticked span it strips the anchor (
#scripts) and the line number (:40or:40-88) and checks that the path exists. - It prints every missing path with its line and exits with code 1 if any are missing.
Run it from the root with node check-map.mjs. We tested it on a fake repository (8 paths, passes; with two files removed, it fails on both) and on a map of our own site with one invented path, which it flagged. A git-ignored .env shows up as missing in a fresh clone: that's expected. The script proves the files exist, not that the description is right; you check that by opening the layer 4 citations yourself.
The first safe change
With the map on its branch, pick the first code change with layer 4 in front of you. Look for something that ticks every box: it sits in a low-risk zone, it has tests nearby or you can write one first, the diff is short enough to read in minutes, and one commit reverts it. Fixing a string, adding a missing test or removing a dependency grep confirmed unused are good candidates. Refactoring the file that changes most is not.
Scroll the figure sideways to see all of it
Do it in a fresh session: the exploration context has done its job, and the docs recommend building from a clean context with a written definition of done. Write that definition as in a spec for AI coding agents, reference @docs/ARCHITECTURE.md if the change touches a marked zone, and review the diff with tests as in reviewing an AI agent's diffs. Why the fresh session works better is in AI coding agent context.
If the high-risk file has no tests and you have to touch it, the first change is a test that pins its current behaviour, even if that behaviour looks odd. That test is what lets you change it later without guessing.
Common mistakes
- Asking for a change in the first session. The agent knows no more about the codebase than you do; you both find the risks in the diff.
- Taking the summary without evidence. Without
file:line, you can't tell what the model read from what it assumed. - Asking for everything in one message. All four layers in one prompt get a shallow answer for each. One layer per message, and correct before moving on.
- Putting the map in CLAUDE.md. It loads in every session and the docs advise against it. It goes in
docs/ARCHITECTURE.mdand you reference it when needed. - Pasting environment variable values. The map holds variable names, never values. Check it before you commit.
- Starting with the file that changes most. That's where a mistake costs most. The first change goes where the risk is low and the diff is short.
Frequently asked questions
Does Claude Code have a read-only mode?
Not by that name. Plan mode is the one the docs recommend for exploring before changing: it reads, explores and blocks edits until you approve. Manual mode (default) runs only reads without asking. If something must never be edited, use a deny rule in your permissions.
Why isn't running /init enough?
/init generates a starter CLAUDE.md with commands and conventions, which is what Claude needs every session. It doesn't tell you which flow handles money, which file has no tests or what to ask the team. Build the map first and run /init after.
What if the codebase is huge, or a monorepo?
Map one package at a time and start Claude in that package's folder. Block reads of generated code with Read deny rules and hand broad exploration to a subagent, as the large codebases guide suggests. The plan mode plan is saved to a file and reloaded after compaction.
How do I know the map didn't make anything up?
Three filters: every fact with its file, "unconfirmed" when there's no proof, and the script that checks the paths exist. Then open the layer 4 citations yourself, since they decide where you'll touch. Whatever the team confirms goes into the open questions section.
Checklist
- Clean git tree and a branch for the map.
- Session in plan mode; no edits before you approve the plan.
- One layer per message: folders, entry points and data, dependencies, risk zones.
- Every fact with
file:lineor marked "unconfirmed". - Environment variables by name, never with their value.
- The map in
docs/ARCHITECTURE.md, not imported intoCLAUDE.md. node check-map.mjspasses with no missing paths./initafter the map, andCLAUDE.mdtrimmed.- The first change: low risk, tested, short diff, in a fresh session.
Saw this on Instagram? Every Reel guide is at ecomlabs.dev/guides.
Written by

Published November 19, 2026 · updated November 20, 2026