Direct answer
Do not begin legacy modernization with a full rewrite. First capture the behavior that matters, including awkward exceptions that may encode real business rules. Use characterization tests to record what the current system does, then make one small structural change with human review.
Claude Code cannot recover tribal knowledge automatically. Root and subdirectory context files can preserve what the team already knows, but missing rules require conversations, logs, production examples and explicit uncertainty. The safe sequence is characterize, change a small seam, compare behavior, review and repeat.
Why legacy code is different
New code usually starts with an intended behavior and an active author. Legacy code may outlive its authors, original requirements and deployment environment. The repository shows mechanics, while the reasons for those mechanics live in support tickets, operational habits and people’s memories.
That gap is tribal knowledge: information the team relies on but has not written down. It can include a rounding exception, a customer-specific bypass, a batch cutoff, a deliberate retry or a workaround for a retired dependency. An agent can read the branch but cannot infer why it exists from the code alone.
Official: The Anthropic large-codebase guidance recommends root and subdirectory context files, read-only exploration, scoped commands and codebase maps. Unknown: It does not claim that an agent automatically recovers undocumented business rules.
A rewrite feels attractive because the old structure is noisy. The risk is that the noise contains compensations for real constraints. Removing a strange retry may be safe, or it may reconnect a production database to a load pattern it cannot handle. Characterization creates evidence before that judgment is made.
Build a legacy risk map
A risk map separates technical uncertainty from business uncertainty. A difficult dependency is not the same as an unknown pricing rule. Capture both, because they require different evidence and different reviewers.
Start with the module’s inputs, outputs, side effects and data stores. Then identify the rules whose origin is unclear. Mark each rule as documented, characterized, disputed or unknown. The label prevents a generated explanation from being mistaken for an approved requirement.
| Risk | Evidence to collect | Owner | Safe response |
|---|---|---|---|
| Undocumented business rule | Support ticket, log example, practitioner interview | Domain owner | Characterize and mark provisional |
| Hidden side effect | Database or queue write | Module maintainer | Assert side effects before refactor |
| Fragile dependency | Version and runtime notes | Platform owner | Isolate behind a seam |
| Generated or vendored code | Generator and source of truth | Build owner | Change the source, not output |
| Missing test environment | Fixtures and service doubles | QA owner | Build a minimal harness |
| Conflicting behavior | Production and test examples | Product and engineering | Decide which behavior to preserve |
Tribal knowledge gaps become worse when every module is treated as equally mysterious. A risk map directs limited human attention to the places where a mistake would matter. Routine formatting cleanup can wait behind an unowned billing exception.
Place the map near the code. A root context file can point to domain boundaries, while a subdirectory file can record local conventions and open questions. The monorepo search and token budget guide helps an agent locate the relevant module without reading the whole repository.
Interview for rules, not architecture
An architecture diagram explains components. A rule interview explains decisions. Ask the practitioner to walk through a real case: what enters the system, which exceptions matter, what output is expected and what happens when a dependency fails.
Do not invent a dialogue or quote for the article. In the actual project, record the interviewee’s role, date, module and the examples they approve. Separate their recollection from verified behavior. Memory is evidence about intent, but it can be incomplete or outdated.
A useful question is “What would surprise a new maintainer?” Another is “Which bug was intentionally left because the fix changed billing?” These questions surface compensations that a code summary may flatten. Capture the answer as a hypothesis until a test or production record supports it.
| Interview prompt | What it reveals | Follow-up evidence |
|---|---|---|
| Which exception looks wrong but is required? | Business compensation | Approved example and test |
| What fails during month-end? | Time-dependent behavior | Batch fixture and logs |
| Which dependency cannot be upgraded alone? | Coupled constraint | Runtime and contract notes |
| What do customers notice first? | Observable priority | Support pattern or metric |
| What should never be “simplified”? | Invariant | Reviewer sign-off |
The Claude Code generated-test oracle bias explains why implementation-derived expectations are risky. Use the interview to define an independent oracle, then compare it with current behavior. When they differ, record a decision instead of silently changing the test.
Characterization tests capture behavior, not approval
A characterization test records what the current system does for a selected input. It does not argue that the behavior is correct. That distinction lets a team preserve a legacy system while it improves structure.
Begin with a narrow, deterministic slice. Control time, randomness, locale and external services. Note inputs, outputs, side effects and relevant error behavior. If the setup is too broad to reproduce, reduce the slice before generating assertions.
Independent: The structured behavioral oracle research describes oracles that encode preserved or changed behaviors, setup constraints and control-flow hints. Use that concept to structure the characterization matrix. It is a test-design approach, not a product guarantee.
| Characterization field | Record | Why |
|---|---|---|
| Behavior ID | Stable name | Connects test, map and review |
| Input | Exact values and environment | Makes the case reproducible |
| Expected output | Current observed result | Preserves behavior |
| Side effects | Writes, messages and state changes | Detects hidden coupling |
| Oracle status | Characterized, approved or disputed | Prevents accidental endorsement |
| Source | Log, fixture or practitioner example | Shows evidence strength |
| Change intent | Preserve or intentionally change | Guides refactor review |
A characterization test can preserve a bug. Mark that possibility explicitly. When the team later decides the behavior is wrong, add a new acceptance test for the intended behavior and keep the old case labeled as legacy. The behavior change then becomes visible rather than being buried in a refactor.
The Claude Code proof-of-work packet is a good home for the matrix. Link each behavior to the test, the source evidence and the reviewer. A green suite without provenance can still encode guesses.
Create a minimal harness
Legacy code often resists tests because it reaches directly into a database, filesystem, clock or remote service. Build the smallest harness that controls those boundaries. Do not begin by containerizing the entire company or mocking every class.
Choose a seam where inputs and outputs are visible. Extract a pure calculation if possible, or inject the dependency at a narrow boundary. Preserve production behavior while the harness makes it repeatable. Structural changes and behavior changes should be separate commits.
A harness needs fixtures that resemble real constraints without copying sensitive production records. Include awkward values, legacy encodings and boundary dates. Synthetic examples are usually enough to exercise the rule if their shape is faithful.
| Boundary | Minimal control | Test evidence |
|---|---|---|
| Clock | Fixed time provider | Cutoff and expiry behavior |
| Database | Transactional test database or double | Exact writes and rollback |
| Queue | Captured messages | Payload and ordering |
| Filesystem | Temporary directory | Paths and generated files |
| Locale | Fixed locale and currency | Formatting and rounding |
| Remote service | Contract fixture | Retry and error behavior |
The Claude Code MCP output truncation guide matters when legacy tools return large logs. Put the failing assertion and decisive error in a compact summary. Preserve the full log separately so truncation does not hide the reason a characterization case failed.
Layered context for agents and people
An agent needs a map, not the whole organizational history. Use layered context so each layer answers a different question. The root points to domains and commands. The package file records local seams and tests. The behavior matrix holds detailed rules and provenance.
That structure also helps humans. A new maintainer can find the open questions without reading every chat transcript. A domain owner can review a small matrix instead of a generated architecture essay.
Official: Custom subagents start with fresh, isolated context. Their initial context includes CLAUDE.md files, but not the parent’s full conversation. The subagent documentation makes the handoff boundary explicit. A legacy exploration subagent therefore needs the module scope and known questions in its task message.
Give a read-only scout a bounded assignment: identify the entry point, list side effects and find existing tests. Ask it to return uncertainty rather than fill gaps with confident prose. The subagent duplicate-work analysis explains how a written brief reduces repeated discovery.
| Context layer | Contents | Update trigger |
|---|---|---|
| Root | Domains, commands, ownership map | Repository structure changes |
| Package | Public entry points and local conventions | Package contract changes |
| Module | Seams, fixtures and known hazards | Refactor or incident |
| Behavior matrix | Inputs, outputs, evidence status | Approved rule discovery |
| Change record | Characterization and review result | Each migration step |
Long agent sessions can compact older turns into a summary. The compaction context-retention test explains that recent turns remain while older turns are replaced. Store durable rules in files, not only in early chat messages. A summary can point to the matrix but should not become its only copy.
Choose a small seam
A seam is a place where one part of the system can be changed without rewriting everything around it. Good candidates include a pure calculation, an external-service adapter, a repository boundary or a module with a clear input and output.
Choose the seam by risk and evidence. A high-value rule with a good harness is a better first target than a visually messy file with unknown side effects. The first change should be small enough that a reviewer can compare old and new behavior line by line.
Use a separate worktree for the experiment. Official: The worktree documentation says active sessions block edits and commands targeting the main checkout. Worktrees share Git metadata, plug-ins, permission approvals and some local skills, so isolation is useful but not complete.
| Seam | Why it helps | Main risk |
|---|---|---|
| Pure calculation | Deterministic tests | Hidden caller assumptions |
| External adapter | Contains dependency churn | Contract mismatch |
| Persistence boundary | Controls side effects | Transaction semantics |
| Module facade | Limits call-site changes | Facade leaks old concepts |
| Generated-code source | Fixes output at origin | Generator may be obsolete |
The parallel-agent worktree pattern helps when several seams are explored at once. Give each agent a separate branch and file ownership. Do not let two agents modernize the same module because the final merge would hide which behavior changed.
A phased migration
Modernization should alternate between evidence and change. A phase that only produces diagrams can continue forever. A phase that changes code without characterization can erase behavior. Tie each phase to a concrete artifact and review decision.
Phase one maps the risk and selects a behavior. Phase two builds the harness and characterization tests. Phase three changes one seam while preserving behavior. Phase four compares outputs and side effects, then gets human review. Phase five removes the old path only after callers and operational dependencies are clear.
| Phase | Artifact | Exit condition |
|---|---|---|
| Discover | Risk map and open questions | Owner and scope named |
| Characterize | Behavior matrix and tests | Cases reproducible |
| Isolate | New seam behind a small interface | Callers still use old behavior |
| Transform | Small structural change | Tests and side effects match |
| Review | Human comparison and decision | Approved behavior recorded |
| Retire | Old path removed | No remaining caller or operational dependency |
A full rewrite violates this sequence because it changes structure, interfaces and behavior at once. It also makes comparison harder. A series of small changes costs more coordination, but it preserves the evidence needed to explain a regression.
The destructive git guardrails matter during retirement. Do not delete the old implementation with a broad cleanup before the new path has been reviewed. Retain a checkpoint or branch until the migration decision is final.
Worked example: preserve a mysterious rounding rule
Suppose a legacy invoice module rounds line items before summing them. The original requirement is missing, and a practitioner recalls that the order was chosen to match an old billing report. These are illustrative inputs, not a real benchmark.
The current behavior can be characterized with a small set of line items. Capture the unrounded values, per-line rounded values, sum and final total. The independent question is whether the rule is “round each line, then sum” or “sum, then round.” Do not decide from the implementation alone.
Derived: If the matrix uses three line-item sets and each records four values, it contains twelve observed values before adding tax or currency cases. That arithmetic describes the worksheet, not a correctness score.
| Case | Line values | Current total | Open question |
|---|---|---|---|
| A | Two values with fractional cents | Characterized result | Is per-line rounding required? |
| B | Three values near a half cent | Characterized result | Does order affect the result? |
| C | One negative adjustment | Characterized result | Is the same rule used for credits? |
The first migration changes the function structure without changing the calculation. Characterization tests guard the current totals. A later behavior change, if the domain owner approves one, gets a new acceptance test and an explicit note that the legacy behavior was intentionally replaced.
The win is a reversible structural improvement with known behavior. The loss is that the original intent may remain uncertain. If no reliable source can resolve it, preserve the current behavior and mark the question open rather than inventing a cleaner rule.
Stop discovery before it becomes a survey
A legacy investigation needs a question and an exit condition. “Understand the billing module” has no finish line. “Find where the subtotal is calculated, list its side effects and identify the existing tests” produces a bounded report. If the agent cannot answer, it should return the missing evidence rather than continue reading unrelated files.
Set the discovery budget by artifacts. Ask for one entry point, one data-flow note, one test list and one open-question list. A larger report is not automatically better. The monorepo search and token budget guide provides scoped retrieval patterns that keep exploration inside the named package.
Use read-only subagents for separate questions, then reconcile their reports. One can trace inputs, another can locate fixtures and another can inspect operational notes. Because subagents start with isolated context, each brief must name the module and the known rules. The subagent duplicate-work analysis explains how to prevent every scout from repeating the same discovery.
When a scout stalls, cancel it and preserve the handoff. A silent agent should not block the migration or trigger a broader search. The subagent hang controls provide the heartbeat and bounded-tool pattern. Note what was already searched so the next session does not repeat it.
Discovery ends when the team can state the next small change and the evidence that will guard it. More reading may be useful, but it belongs to a new question. This keeps modernization moving while leaving unknown rules visibly open.
Measure the migration by preserved behavior
A migration scorecard should not reward the number of rewritten files. Track characterized behaviors, reviewed seams, unresolved questions and regressions found before release. Those measures reflect evidence quality and risk reduction more directly than code volume.
The cost per verified change framework can include harness construction, interviews, generated changes and human review. Use the LLM cost calculator only with known prices and token counts. A subscription quota is not an API price, and a cheaper rewrite is not a win if it changes an unowned rule.
Establish a baseline for each phase. Compare test results, side effects and open questions before and after the seam change. If the number of unresolved questions rises, the migration may be discovering real debt rather than failing. The important response is ownership, not hiding the gap.
A tooling change should not erase that baseline. The single-model lock-in and exit-cost analysis makes the portability problem concrete. Store behavior matrices, fixtures and review decisions in repository-owned formats so a later agent or provider can use the same evidence.
Review the evidence, not just the diff
A clean diff can hide a semantic change. Review the characterization matrix, side effects and caller assumptions alongside the code. Ask which behavior was preserved, which was changed and which remains unknown.
Use a checklist that forces those questions. Every changed seam should have a named test set and a reviewer who understands the domain. If the reviewer only understands the framework, the business decision still needs an owner.
| Review question | Evidence | If missing |
|---|---|---|
| What behavior was preserved? | Characterization tests | Stop the refactor |
| What behavior changed intentionally? | Approved acceptance case | Revert or clarify |
| Which side effects were checked? | Database, queue or file assertions | Add harness coverage |
| Who owns the remaining uncertainty? | Risk map owner | Assign before merge |
| Is the old path still needed? | Caller and operations check | Keep it behind a flag |
The auto-mode classifier limitations are relevant when review prompts become tiring. A classifier can reduce routine interruptions, but it cannot decide whether an undocumented rule is correct. Make the domain review explicit.
Generated tests also need an independent oracle. The code-first oracle bias research warns that implementation-derived tests can inherit faults. In legacy work, distinguish “this is what the code does” from “this is what the business requires.”
Honest loss and data gap
Unknown: No supplied source guarantees recovery of tribal knowledge, successful modernization or a fixed reduction in risk. Some rules may exist only in a former employee’s memory or an unrecorded operational habit. If the team cannot find evidence, the honest result is an open question.
Characterization has limits. Selected cases do not cover every input. A harness can reproduce the wrong environment. A practitioner’s recollection can conflict with production behavior. Small changes reduce blast radius but slow delivery, and a seam can leak old assumptions into the new structure.
The practical win is a preservation trail: known behavior, tested side effects and explicit uncertainty. The honest loss is that modernization remains partially investigative. Revisit the matrix after incidents, regulatory changes or newly discovered examples. Do not let a generated summary convert an unknown rule into a confident requirement.
Practical migration checklist
- Name the module, business owner and highest-risk unknown.
- Note inputs, outputs, side effects and data stores.
- Interview for exceptions and compensations, then verify examples.
- Build a minimal deterministic harness.
- Write characterization tests and label their evidence status.
- Choose one seam and one behavior to preserve.
- Make the structural change in a separate worktree.
- Compare outputs and side effects with the matrix.
- Get domain review before retiring the old path.
- Preserve open questions and update them when new evidence appears.
Store durable context near the code. The Claude Code settings-file secret guide is a reminder not to place credentials in context or fixtures. Use synthetic data that preserves the shape of the rule without copying customer records.
Bound exploration so it does not become an endless survey. The subagent hang and timeout controls provide a recovery pattern when a scout stops producing events. A silent legacy exploration task needs cancellation and a written handoff, not another unbounded agent.
Use the privacy and retention analysis when real examples are necessary. Minimize what leaves the environment and record the approved handling path. Legacy data often contains personal or commercially sensitive fields that a test fixture does not need.
Practical OpenAI-format alternative with One AI API Key
If you want to compare coding agents on a synthetic legacy fixture, the 46 live free model IDs are available through OpenAI-format agents. The free lane shares 100 requests and 5,000,000 tokens per day per account, resets at 05:30 IST or 00:00 UTC, and allows one request in flight per key. Accounts can have up to three keys.
Use the quickstart for the base URL and first request. The pricing page explains prepaid billing, the sign-up page starts an account, and the privacy policy covers logging defaults and upstream-provider terms.
The documented Claude Code route is unavailable because all four Claude IDs were marked unavailable on November 27, 2026. Free IDs are OpenAI-format only. Never claim they work inside Claude Code. A different model does not replace characterization tests, domain interviews or human review.
New accounts receive $10 credit with no card, and billing is prepaid with no subscription or seat fee. The published controls include prompt logging off by default, per-key spend caps, expiry dates, allowed-model lists and request-level usage records. Upstream providers receive requests under their own terms. Exclude real customer records from the comparison fixture and use the per-key controls reference to limit the evaluation credential. Do not promise guaranteed automatic fallback across models.
For a legacy-workflow comparison, configure an OpenAI-format agent with https://api.oneaiapikey.com/v1, one key and a selected free ID against a synthetic module with a known behavior matrix. Ask for characterization tests and one small seam change, then compare preserved outputs, side effects and open questions. Note the model ID, request count, fixture version and reviewer decision. Hold the behavior matrix unchanged during the comparison. Do not use real customer data or treat generated confidence as recovered business intent. The exercise tests process discipline, not automatic tribal-knowledge recovery.
FAQ
Can Claude Code recover undocumented business rules automatically?
No. It can find code patterns and help draft questions, but missing intent requires external evidence and human judgment. Mark unresolved rules as unknown.
What is a characterization test?
It records current behavior for a selected input. It preserves evidence during refactoring but does not prove the behavior is correct.
Why not start with a full rewrite?
A rewrite changes structure, interfaces and behavior together, making regressions hard to isolate. Small seam changes keep the comparison reviewable.
Should characterization tests be deleted after modernization?
Retain them while they protect behavior that still matters. Retire a test only with an explicit decision and replacement coverage for the intended behavior.
What if the code and the practitioner disagree?
Capture both sources, reproduce the current behavior and ask the domain owner to decide. Do not let the agent silently choose one as the requirement.
More Claude Code troubleshooting
- Claude Code WSL IDE environment-variable diagnosis
- Claude Code WSL2 memory-warning breakdown
- Claude Code Windows subagent MCP memory leaks
- Claude Code VS Code WebSocket regression test
- Claude Code desktop browser-pane crash recovery
- Claude Code background subagent running-count diagnosis
- Claude Code subagent stop and resume semantics
- Claude Code compaction cost worksheet
- Claude Code prompt-caching break-even math
- Claude Code idle-session cache-miss analysis
- Claude Code long-context prefill latency test
- Claude Code usage tracking and cost API guide
- Claude Code task budgets versus hard stops
- Claude Code 429 error decision tree
- Claude Code billing-dispute evidence packet
- Claude Code refund and support policy guide
- Claude Code hallucinated-package supply-chain controls
- Claude Code GitHub Actions secret boundaries
- Claude Code repository-hook security review
- Claude Code extension-trojan remediation steps
- Claude Code CVE-2026-55607 sandbox boundary
Sources
- Anthropic large-codebase context and exploration guidance
- Independent structured behavioral oracle research
- Claude Code subagent context isolation
- Claude Code worktree isolation
- Claude Code compaction behavior
- Claude Code troubleshooting guidance