Pin legacy .NET pricing with a golden master before an AI agent touches it
If you point a coding agent at a ten-year-old pricing engine, it will often try to be helpful. Math.Round(x, 2) becomes Math.Round(x, 2, MidpointRounding.AwayFromZero) because "that is what people expect." net > 500m becomes net >= 500m because "500 should qualify for free freight." Both look like bug fixes. Both change the prices customers already see.
I have been writing .NET for twenty-one years, and I still would not try to remember every quirk in a 2014 pricing class by hand. The reliable move is older than AI agents: characterize the actual behaviour, then refuse any rewrite that does not match it. Michael Feathers called this a characterization test. In a migration, the legacy system is the specification.
This article walks through the method I used on a fictional parts portal, Meridian, whose pricing rules moved from .NET Framework to .NET 10. The code is in a public companion repository, and the tests in that repository pass. I am not claiming results from a production estate.
Example tests are not enough
A first attempt usually looks like three unit tests: one GOLD customer, one SILVER customer, one export order, with expected totals typed in by a person. Those tests are easy to read. They are a weak safety net for two reasons.
They only cover the cases someone thought of. Migration bugs live in the cases nobody wrote down: midpoint rounding, an exact freight boundary, a lowercase tier code, a missing region.
They also invite the wrong kind of review. When expected values are written by hand, the person writing them reasons about what the code should do. That is how a reviewer, human or model, approves a "tidier" rounding change: both agree it looks right.
A golden master inverts this. You build a large set of inputs, run them through the unchanged legacy code, and record every output to a file. That file is the approved behaviour. The new code must reproduce it exactly. Nobody has to guess the right answer. The old system already answered.
Run the real legacy code
Where the logic lives in a class library and does not touch HttpContext or the database, compile the original source unedited. Meridian's pricing engine uses only the base class library, so the repository links the 2014 files into a netstandard2.0 project that a .NET 10 test assembly can call:
<!-- src/Meridian.Legacy.Pricing/Meridian.Legacy.Pricing.csproj --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>7.3</LangVersion> <Nullable>disable</Nullable> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> </PropertyGroup> <ItemGroup> <Compile Include="..\..\legacy\MeridianPortal.Core\Pricing\PricingEngine.cs" Link="Legacy\PricingEngine.cs" /> <Compile Include="..\..\legacy\MeridianPortal.Core\Pricing\QuoteModels.cs" Link="Legacy\QuoteModels.cs" /> </ItemGroup> </Project> LangVersion 7.3 matches what a 2019 compiler accepted. Repository-wide analysers are switched off for this project only: the legacy files are evidence, not something to clean up. The repository forbids edits under legacy/.
This is not identical to running the same files on .NET Framework. Culture data, double formatting, and some string comparisons can differ between Framework on Windows and modern .NET on Linux. For pure decimal arithmetic the risk is lower; it is not zero once culture or floating point is involved. The rigorous approach is to record the golden file on net48 on a Windows agent, then confirm that the .NET 10 run of the same legacy source agrees. The companion repository's CI runs on Linux, so it records on .NET 10 only. Treat that as a documented limitation, as you would on a real project.
Build a deterministic corpus
A good corpus has two parts: hand-picked edge cases that target known risks, and generated cases that explore the space between them.
// tests/Meridian.Characterization.Tests/CorpusGenerator.cs (abridged) private static readonly string?[] Tiers = ["GOLD", "SILVER", null, "gold", "BRONZE"]; private static readonly string?[] Regions = ["NORTH", "SOUTH", "EXPORT", null, "north", "WEST"]; private static readonly int[] Quantities = [-1, 0, 1, 2, 7, 49, 50, 51, 99, 100, 101, 250]; public static IReadOnlyList<CorpusCase> Build(int generated = 600) { var cases = new List<CorpusCase> { new("edge-empty", "GOLD", "NORTH", []), new("edge-qty-49", null, "NORTH", [new("BLT-M8-40", 49, 1.10m, 0.02)]), new("edge-qty-50", null, "NORTH", [new("BLT-M8-40", 50, 1.10m, 0.02)]), new("edge-net-exactly-500", null, "SOUTH", [new("VLV-200", 4, 125.00m, 6.4)]), new("edge-gold-lowercase", "gold", "NORTH", [new("VLV-200", 2, 129.90m, 6.4)]), new("edge-region-null", "SILVER", null, [new("VLV-200", 1, 129.90m, 6.4)]), new("edge-midpoint-discount", "GOLD", "EXPORT", [new("GSK-12", 1, 0.60m, 0.0)]), // 14 hand-picked cases in the full file }; uint state = 20141103; uint NextUInt() { state = unchecked((state * 1664525u) + 1013904223u); return state; } int Pick(int n) => (int)(NextUInt() % (uint)n); for (int i = 0; i < generated; i++) { int lineCount = 1 + Pick(4); var lines = new List<CorpusLine>(lineCount); for (int j = 0; j < lineCount; j++) { // Prices with 2–4 decimal places produce rounding midpoints. decimal price = (NextUInt() % 2_000_000) / 10_000m; double weight = (NextUInt() % 5000) / 1000.0; lines.Add(new(Codes[Pick(Codes.Length)], Quantities[Pick(Quantities.Length)], price, weight)); } cases.Add(new($"gen-{i:D4}", Tiers[Pick(Tiers.Length)], Regions[Pick(Regions.Length)], lines)); } return cases; } A few choices here matter more than they look.
The generator is self-contained. It uses a linear congruential generator with a fixed seed, not System.Random, whose algorithm is an implementation detail and has changed between runtimes. The same 614 cases (14 edges plus 600 generated) appear on every machine.
The value lists are chosen, not random. Quantities sit on both sides of each volume break (49/50/51, 99/100/101), plus zero and negative values. Tiers include lowercase gold and an unknown BRONZE. Regions include null, lowercase, and an unknown WEST. Each value exists because a read of the code suggested a risk.
Prices go to four decimal places so rounding midpoints are common. That is what you need to tell banker's rounding from other modes.
Every case has a stable identifier. A failure names edge-net-exactly-500 or gen-0417, not "case 423".
Take the freight rule as an example. The legacy engine waives freight only when net is strictly greater than 500. The case edge-net-exactly-500 is four lines at $125.00, which comes to a net of exactly $500.00. Freight is still charged. If someone later "fixes" the comparison to >=, this case is the one that moves.
Record the legacy output, then compare
The golden-master tests do two jobs. First, the legacy engine must still match the approved file, which guards the harness itself. Second, the modern engine must match the legacy engine on every case.
// tests/Meridian.Characterization.Tests/GoldenMasterTests.cs (abridged) [Fact] public void GoldenMaster_LegacyEngine_MatchesApprovedFile() { var actual = Corpus.Select(c => Runners.RunLegacy(c)).ToList(); var path = ApprovedPath(); if (Environment.GetEnvironmentVariable("GOLDEN_RECORD") == "1") { File.WriteAllText(path, JsonSerializer.Serialize(actual, Json)); Assert.Fail($"Recorded {actual.Count} cases to {path}. Review the diff, then run again without GOLDEN_RECORD."); } var approved = JsonSerializer.Deserialize<List<QuoteSnapshot>>(File.ReadAllText(path))!; var mismatches = approved.Zip(actual).Where(p => !p.First.SameAs(p.Second)).ToList(); Assert.True(mismatches.Count == 0, "Legacy output drifted from the approved file:\n" + string.Join("\n", mismatches.Take(10).Select(m => $"approved {m.First}\nactual {m.Second}"))); } [Fact] public void GoldenMaster_ModernEngine_MatchesLegacyForEveryCase() { var mismatches = Corpus .Select(c => (Legacy: Runners.RunLegacy(c), Modern: Runners.RunModern(c))) .Where(p => !p.Legacy.SameAs(p.Modern)) .ToList(); Assert.True(mismatches.Count == 0, $"{mismatches.Count} of {Corpus.Count} cases differ:\n" + string.Join("\n", mismatches.Take(10).Select(m => $"legacy {m.Legacy}\nmodern {m.Modern}"))); } Recording is deliberately noisy. Setting GOLDEN_RECORD=1 writes the file and then fails, so a recording run can never be mistaken for a passing run. The new file shows up as a diff in version control, where a person reviews it.
The legacy runner also pins the thread culture to en-US for the call, because the original site ran with <globalization culture="en-US" /> and IIS applied that to every request. The display string is part of the contract. On a server set to de-DE, the same total would have been formatted differently. The modern port makes the culture explicit, so it no longer depends on the machine.
Prove the corpus can catch the mistakes you fear
A green golden master tells you the new code matches the old code on those inputs. It does not tell you the inputs are good enough. That is what mutation guards are for: small tests that implement the most likely wrong versions of the logic and assert that the corpus can tell them apart from the legacy behaviour.
// tests/Meridian.Characterization.Tests/MutationGuardTests.cs (abridged) [Fact] public void Corpus_Detects_SwitchToAwayFromZeroRounding() { int differing = Corpus.Count(c => Runners.RunLegacy(c).Total != TotalWith(c, MidpointRounding.AwayFromZero, freeFreightInclusive: false)); Assert.True(differing > 0, "No case distinguishes ToEven from AwayFromZero rounding."); } [Fact] public void Corpus_Detects_InclusiveFreeFreightThreshold() { int differing = Corpus.Count(c => Runners.RunLegacy(c).Total != TotalWith(c, MidpointRounding.ToEven, freeFreightInclusive: true)); Assert.True(differing > 0, "No case sits exactly on the 500.00 free-freight boundary."); } TotalWith is a deliberately tidied re-implementation with those two switches. The two mutations are the ones reviewers, human or AI, most often propose as improvements. If someone later trims the corpus to make tests faster and drops the boundary case, these tests fail and say why.
If one of these starts failing, the corpus has lost coverage, not the production code.
Protect the golden files
An agent told to "make the tests pass" will, sooner or later, re-record the golden file. Defend that file in layers.
Tell the agent, in AGENTS.md and in tool permissions, that files under golden/ are off limits. Fail CI if those files change without an explicit [golden-approved] marker in the commit message. Put CODEOWNERS on the golden directories so a person has to approve the pull request.
Re-recording is a human decision. It belongs in a commit that points at a written decision: Sales Operations agreed to change the freight threshold, or a named quirk is being retired. Until then, the characterization suite is the contract.
In the modern port, name each preserved quirk in the code (QUIRK-1 for banker's rounding, QUIRK-3 for the exclusive freight threshold) and list them in a short document the reviewers can read. Hidden behaviour that only lives in a JSON file of 614 rows is hard to discuss. Named behaviour can be kept, or changed on purpose.
Once the legacy system is retired and the business has reviewed those quirks, many of these tests can become ordinary, intention-revealing unit tests. Some quirks will be fixed by an explicit decision, and the golden file is re-recorded once. Until that point, keep the oracle.
Go deeper
I walk through this method, including the mutation guards, the culture pin, the review gates, and the rest of the Meridian migration, in Modernizing Legacy .NET with AI Agents. The book was drafted with the help of AI tools and then reviewed and edited. Every C# listing that comes from the companion repository was compiled with the .NET 10 SDK and covered by that repository's tests.
- Book (ebook, until the Kindle edition is live): Modernizing Legacy .NET with AI Agents on Gumroad
- Companion repository: github.com/qmmughal/legacy-dotnet-modernization-ai
I am Qaiser Mehmood, a software architect focused on .NET, Blazor, Python, and agentic AI. More of my work is at github.com/qmmughal.