Record what legacy code does today with golden-master tests before Claude Code edits it, then guard the recording against agent rewrites.
To use Claude Code on a legacy codebase with no tests, record what the code does today before the agent changes a line, then make every change prove it left that recorded behavior alone. The recording is a golden master, also called a characterization or approval test: run the untouched program over real inputs, save the outputs, and diff against them after each step. You do not need to understand the internals first, which is the point.
Disclosure: we build TLM Forge, a process layer for Claude Code, so weigh the product section accordingly. Almost everything below works with plain Claude Code and a shell.
Why every change to untested code feels risky
Developers ask about this in public. One Ask HN thread is titled "How are you using AI code assistants on large messy legacy code bases?" and its author describes a codebase more than 20 years old, written by many developers in many styles. The replies vary: suggestions include writing documentation for the agent to read, using plan mode and working in small steps, and one reply says to skip the agent and do it the old way. One reply suggests noting the outputs before a refactor and checking them again afterward. That last idea is the technique this post turns into a procedure.
Sources: Ask HN: How are you using AI code assistants on large messy legacy code bases?, Hacker News reply by mc7alazoun
Michael Feathers states the underlying problem plainly: much software needs changes, and the people making them do not know enough about what it does. He adds, in his words: "When a system goes into production, in a way, it becomes its own specification." His example is a bug fix that drew complaints from users who had depended on the behavior he removed.
Sources: Michael Feathers, Characterization Testing
An agent raises the stakes. It can touch many files before you read the first diff, and nothing in undocumented code tells it what the old behavior was holding up. The Claude Code best-practices page describes what happens when there is no check to run: "In practice that makes you the test suite, and every mistake sits there until you happen to notice it." On untested code, that sentence describes the default.
Sources: Claude Code docs: Best practices
What a golden master is, and what it is not
The ApprovalTests.Python README describes the mechanism in two sentences: "Approvals work by comparing the test results to a golden master. If no golden master exists you can create a snapshot of the current test results and use that as the golden master." Feathers frames the purpose as documenting what a system actually does, not checking for the behavior you wish it had. The names vary by community. One author who compared them concludes "Yes, Approval and Characterization Tests are the same thing" and puts the different names down to the lack of a recognized standard.
Sources: ApprovalTests.Python README, Michael Feathers, Characterization Testing, Nicolas Carlo on DEV Community: What's the difference between Regression Tests, Characterization Tests, and Approval Tests?
A golden master tells you that behavior changed. It never tells you the behavior is correct. Keep those two questions apart, and do not let a green check stand in for the second one.
That separates it from the failure described in How to Test AI-Generated Code Properly, where a model derives expected values from the implementation and the test proves nothing about intent. A golden master makes no claim about intent. It asks only whether behavior moved, and a test derived from what the code does is the right tool for that.
Step 1: map the seams without letting the agent edit
Start in plan mode. The permission-modes page says it tells Claude to research and propose changes without making them, and you enter it with Shift+Tab or with claude --permission-mode plan. In a large codebase, the built-in Explore subagent is described as a read-only agent for searching and analyzing code, and the common-workflows page suggests delegating exploration so that only the findings come back to your main conversation.
Sources: Claude Code docs: Permission modes, Claude Code docs: Subagents, Claude Code docs: Common workflows
Prompt to paste in plan mode: "Read only, edit nothing. For the module I name, list every entry point I can call from a test or the command line. For each one, say what it reads (files, database, clock, network, environment variables) and what it writes. Rank the entry points from closest to the outside world to deepest inside."
You are looking for a seam to pin. Feathers says the hardest part of characterization testing is breaking dependencies around the code well enough to run it in a test harness, so pin from the outside first. The outermost seam you can run repeatably usually needs the least dependency-breaking. Pin only the area the next change can reach, not the whole application.
Sources: Michael Feathers, Characterization Testing
| Seam to pin | What it pins | What it misses | Typical setup effort |
|---|---|---|---|
| Command line or batch job | stdout, stderr, exit code and files written | Internal logic that never shows in the output | Low: run the program once per fixture |
| HTTP endpoint | Status, headers and body for recorded requests | Rows written or messages sent, unless you capture them too | Medium: needs a running app and a test database or fakes |
| Database state after an operation | Rows, files or queue entries the code leaves behind | What the caller sees in the response | Medium: needs seed data and a reset between cases |
| A single function | Return values and exceptions for given arguments | Wiring between functions and hidden dependencies | High when it reads globals, the clock or the network |
Step 2: record outputs by running the code, not by reading it
Feathers demonstrates the manual method. Write a test with a placeholder expectation, run it, and read the real value from the failure message. About a test whose expectation he had guessed correctly, he asks: "We made a good guess, but why are we guessing at all?" A model that reads legacy code and writes the expected output is guessing in the same way, only faster, and the surprising cases are where a guess is least reliable. Have it write the harness, then produce the golden files by executing the program.
Sources: Michael Feathers, Characterization Testing
Prompt for the recording step: "Write a script that runs the program once for each file in tests/fixtures and saves stdout, stderr and the exit code to a matching file in tests/golden. Produce every golden file by running the program. Do not write an expected value by hand, and do not edit anything outside tests/."
Inputs matter more than the harness. Real samples, such as anonymized production files, requests copied from logs and the odd files support keeps in a folder, carry the oddities users actually sent, which invented inputs tend to miss. Add boundary values for every condition you found in Step 1: the value at the limit, one below and one above. Capture stderr and the exit code too, because both are behavior.
For a command-line program or batch job, two one-liners are enough. They assume the program is ./legacy and each fixture is a file named tests/fixtures/NAME.in.
- Record once, on the untouched code:
mkdir -p tests/golden; for f in tests/fixtures/*.in; do { ./legacy < "$f" 2>&1; echo "exit=$?"; } | sed -E "s/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]+Z/<TS>/g" > "tests/golden/$(basename "$f" .in).out"; done - Check after every change:
fail=0; for f in tests/fixtures/*.in; do { ./legacy < "$f" 2>&1; echo "exit=$?"; } | sed -E "s/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]+Z/<TS>/g" | diff -u "tests/golden/$(basename "$f" .in).out" - || fail=1; done; test $fail = 0
The check prints a unified diff for each fixture whose output changed and fails if any did. A fixture with no golden file yet also fails it. A toy report script with an undocumented 10 percent bulk discount above 100 units, and a blank-field line that aborts the run with exit code 3 before the total prints, shows the idea: the golden files record both quirks without anyone having to notice them first.
Step 3: scrub what changes between runs
The Jest documentation says generated fields such as IDs and dates will "force the snapshot to fail on every run," and that tests should be deterministic. The same holds for any golden file. Common sources of variation:
Sources: Jest docs: Snapshot Testing
- Timestamps and dates.
- Generated IDs, UUIDs and random numbers.
- Absolute paths, hostnames and process IDs inside stack traces and warnings.
- Time zone and locale.
- Ordering that comes from hash tables, directory listings or parallel threads.
Freeze the source of variation where you can, with a fixed clock or a seeded random generator. Scrub the output where you cannot, as the sed expression in the record command does for ISO timestamps. Keep scrubbers narrow. A rule that masks every number hides the very changes you are watching for, and a scrubber the agent can edit is a hole in the net.
Step 4: prove the net can fail
A green check from a net with holes is worse than no check, because it looks like evidence. Before any change, break the code on purpose and confirm the check goes red. Nicolas Carlo, who compares these test names on DEV Community, says he introduces deliberate bugs to verify at least one test fails. In the toy script, changing the bulk-discount condition from greater-than to greater-or-equal turned the 100-unit fixture red, which is why a boundary fixture belongs beside every condition. If the check stays green, no fixture tells the sabotaged code from the original, so add one that does, then revert the sabotage. Commit the baseline first so that reverting is a single git command.
Mutation testing automates the same idea across a whole module, and Mutation Testing for AI Code: Why Coverage Lies explains how to read the results. Anthropic frames the underlying requirement for modernization projects as a certificate: conditions every change must meet, each of which should be "checkable without a human in the loop." Its list includes "Current and target versions produce the same output from the same input, which can be live, recorded, or Claude-generated." A golden master is that same-output condition, recorded once.
Sources: Claude blog: How to prepare for AI-driven code modernization projects
Step 5: read the recording for surprises, then leave them alone
Have Claude read the golden files, still without editing anything, and list every output that looks like a bug, a hack or a dead branch. Save the list as a QUIRKS file for a human to triage, and fix nothing during recording. Feathers advises that if you have not determined that an uncovered behavior is a bug, it is often a good idea to leave the test in place. His own story of a bug fix that users then complained about shows why.
Sources: Michael Feathers, Characterization Testing
When you do decide to change behavior, make it its own commit. An accepted Software Engineering Stack Exchange answer on fixing a bug that a characterization test pins describes the sequence: update the golden master, by hand if necessary, so it predicts the new behavior, confirm the old code fails it, change the code, confirm it passes. The same answer says these tests should not be expected to live forever, and should be retired once other, less brittle tests cover the behavior.
Sources: Software Engineering Stack Exchange: characterization tests when a bug is fixed
Step 6: lock the right files at the right time
A golden master works only while it stays the record of the untouched code. The Jest documentation says the point of reviewing snapshots in pull requests is partly to "fight against the habit of regenerating snapshots when test suites fail instead of examining the root causes of their failure." An agent facing a red check has the same shortcut. How to Stop Claude Code Changing Tests to Pass covers that habit in general. For golden files, lock in two phases.
Sources: Jest docs: Snapshot Testing
- While recording, the production code must not change, or the golden files will describe something other than the untouched code. Deny edits to it in .claude/settings.json with
{ "permissions": { "deny": ["Edit(/src/**)"] } }, replacing src with your source directory. - While changing code, commit the baseline, then lock the goldens. This settings file denies edits to tests/golden and adds a Stop hook that exits with code 2 whenever anything under that folder is modified, added or deleted since the last commit, which sends Claude back to work with the message from stderr:
{ "permissions": { "deny": ["Edit(/tests/golden/**)"] }, "hooks": { "Stop": [ { "hooks": [ { "type": "command", "command": "git -C \"$CLAUDE_PROJECT_DIR\" status --porcelain -- tests/golden | grep -q . && { echo golden files changed, restore them >&2; exit 2; }; exit 0" } ] } ] } }
Know the limits, which the documentation states. Read and Edit deny rules apply to the built-in file tools, to file commands Claude Code recognizes in Bash such as sed and tee, and to redirections, but not to a Python or Node script that opens files itself, which is how a regenerate-the-goldens script would write them. The hook catches that case afterward, but a Stop hook has a cap: after it has continued the turn eight times in a row, Claude Code overrides the next block and ends the turn, and the count resets whenever Claude calls a tool. Your own check stays the last line, so before merging, confirm the branch changes nothing under tests/golden unless it is the branch that re-records them. Claude Code Permissions: What Deny Rules Miss covers the wider gaps.
Sources: Claude Code docs: Permissions (Read and Edit rules), Claude Code docs: Hooks reference (Stop)
Step 7: change in small steps and demand the output
The common-workflows page advises refactoring in small, testable increments and asking that changes maintain the same behavior. After each step, tell Claude to run the check and paste the output. The best-practices page recommends asking for evidence, meaning the command it ran and its output, and says a bare "All tests pass" tells you very little. For the wider habits, such as small commits and reading every diff, see How to Refactor With AI Without Breaking Things.
Sources: Claude Code docs: Common workflows (Refactor code), Claude Code docs: Best practices
Prompt for each change: "Make this one change: [describe it]. Run the golden check after each edit and paste the full output. If any golden diff appears, stop and tell me. Do not touch tests/golden and do not rerun the record command."
What a golden master cannot see
- Side effects. A program can print identical output while writing different rows, sending different email or calling another service differently. Pin the state it leaves behind, such as a table dump or a list of files written, or record outgoing calls through a fake.
- Inputs you did not record. Behavior on input shapes missing from the fixtures is unpinned. Add a fixture each time a new real case turns up.
- Timing, concurrency and load. A diff of outputs says nothing about speed, locking or races.
- The bytes of the source files themselves, covered next.
Legacy code often sits in files that are not UTF-8. One user-filed Claude Code issue describes a Windows-1252 codebase where, the reporter says, the Edit and Write tools replace undecodable bytes with the Unicode replacement character and write the whole file back as UTF-8, corrupting every accented character in it, not only the edited lines. Other users in that thread added reports from a CP852 codebase and a VB6 one. These are individual reports, not measurements. The release notes for Claude Code 2.1.296 (October 9, 2026) say Edit and NotebookEdit refuse edits to files that are not valid UTF-8, such as Windows-1252, Shift-JIS and GBK, and the notes for 2.1.299 (October 14, 2026) say Write refuses to silently convert such files to UTF-8. A refusal means the agent needs another route, so agree on the route before it starts.
Sources: anthropics/claude-code issue 64601, Claude Code changelog
After each step, run git diff --stat. A one-line change that rewrites a whole file points to an encoding or line-ending problem, and an output-based check may never show it.
Decisions that stay with a human
- Whether a surprising output is a bug or a behavior someone relies on.
- Which fixtures represent real use.
- Whether the check is strong enough to start, which the break-it-on-purpose test answers.
- When to re-record the goldens, and when to retire them.
Where TLM Forge fits
TLM Forge sizes each task as Light, Medium or Deep. It tells Claude to build tests first, and on Medium and Deep tasks it shows a design for your OK before building. On legacy work, use that pause: check whether the design changes any behavior your golden files record, and whether it plans to touch the golden files themselves. The limits are plain. Tests-first is an instruction, and no hook checks test results. Record the golden master yourself (Steps 1 to 6) before you start. Light tasks do not pause for your OK on a design, so check how a change was sized before relying on it.
Frequently asked questions
01Can Claude Code write characterization tests for legacy code?
Yes, but the expected values should come from running the untouched program, not from the model reading the code. Ask it to write the harness and generate the golden files by executing the code, keep production code read-only during that step, and review the recorded outputs yourself.
02What if the legacy code has no seams to test at?
Pin it from the outside. Run the program or endpoint with real inputs and save stdout, the exit code, and any files or database state it leaves behind. An outer seam usually needs less refactoring than a unit test does. Break dependencies afterward, in small steps, under that net.
03Should golden files record behavior I think is a bug?
Yes, until a person decides otherwise. Users may depend on the current behavior, and a recorded bug lets you see when a change alters it. Keep a list of suspected bugs, fix them in separate commits, and update the golden files by hand with a reviewed diff.
04How do I stop Claude Code from regenerating golden files to turn a check green?
Deny edits to the golden folder in permissions, add a Stop hook that exits with code 2 when that folder has changes, and check the diff before you merge. Deny rules do not cover scripts that write files themselves, so the hook and your own review both matter.
05How many fixtures does a golden master need?
Enough to reach every branch of the code you are about to change, with boundary values on each condition. There is no universal count. Test it by breaking a condition on purpose: if nothing fails, add a fixture that exercises that condition.