DEV Community

When AI Ports a Legacy System, How Do You Check It Copied Correctly? Functional Core, Rule Lists and State-Machine Property Tests

Working Notes and Maturity Labels

These are working notes on a method, not a framework recommendation.

Each main step is labelled with its maturity: Executed (run on a simplified example model, with results), Built (tooling written, verified only on the example), Agreed, not yet applied (process decided, not yet used on a real module). Please read the three separately.

Conclusion First

AI writes code fast. In a port-style rewrite the bottleneck is no longer writing, it is knowing whether what was written is right. Existing example tests only cover the path someone thought of, and what breaks is usually a sequence of operations nobody thought of. So we added property tests alongside the example tests.

The approach is four things stacked together:

  • Squeeze the screen logic into a functional core, so side effects become data you can inspect;
  • Extract business rules from the legacy code, then check them against existing data, with a source citation for every rule;
  • Use state-machine property tests to let the tool hunt for counterexamples, and verify that "removing the fix gets caught";
  • Use an acceptance gate to check that the implementing AI did not touch the protected tests.

Background: The Hard Part of Porting Is Proving It Behaves the Same

We are rewriting an existing system onto a new architecture, and most of the code is written by AI. The rule is screens and behaviour are ported as-is. Even the old system's defects are copied first; whether to fix one is a human decision.

Another rewrite project hit a textbook case in its test environment. On a detail page, pressing Copy made the old code copy the form but not clear the attachment area. After a new record number was entered, the attachment area still showed the original record's attachments and delete buttons, and each delete button sent the primary key of its own row. So pressing delete on the new record deleted the original record's attachment. It was only found after it actually happened.

The fix came with example tests, but they verified only half of it. More on which half below.

Step 1: Extract the Logic Into a Functional Core (Executed)

Write the logic behind the screen as a pure function: step(state, action) → { newState, effects }

Actions: open a record, Copy, enter the record number, pick a file, upload, delete. Effects: what should happen on the server, such as "delete this attachment" or "upload this file".

The core never calls an API. It returns these, and the shell (a React component plus the API) executes them.

The benefit is concrete: tests don't need a server. Looking at the returned effects tells you exactly which row a click would delete.

The cost is just as concrete: every stateful screen gets an extra layer, and core tests only check that "deciding what to do" matches the written properties. Whether the shell actually does it still needs E2E or example tests.

Step 2: Write Down What Must Never Happen, and Let the Tool Find Counterexamples (Executed)

Alongside the example tests, write properties, checked after every step:

  1. Delete only deletes attachments of the record currently on the form. A violation means deleting another record's attachment from the new record (the bug that actually happened).
  2. The attachment area only shows this record's attachments. A violation means the screen shows another record's attachments.
  3. Every uploaded file was picked on this record's form. A violation means a file picked but not yet sent on the previous record gets uploaded to the new one.

The generator uses fast-check: random action sequences of up to 20 steps, with record numbers deliberately drawn from only 3 values so that "same record / different record" collisions are likely. On the fixed version, each property passed 1,000 runs (fast-check's default is 100).

The sketch below shows property 1 only, leaving out types, generators and test-framework setup. Both sides compare the record number; that detail comes back later:

fc.assert(
  fc.property(
    fc.array(actionArb, { maxLength: 20 }),
    (actions) => {
      let s = initialState;
      for (const a of actions) {
        const { state, effects } = step(s, a);
        for (const e of effects) {
          // a delete must target the record that was on the form when delete was pressed
          if (e.t === "deleteRemote") assert.equal(e.docNo, s.docNo);
        }
        s = state;
      }
    }
  ),
  { numRuns: 1000 },
);

Results:

  • Fixed (1,000 runs each): Property 1 Pass, Property 2 Pass, Property 3 Pass
  • Fix removed (fixed seed): Property 1 Caught, Property 2 Caught, Property 3 Caught

Three things worth noting:

The counterexample property 1 shrank to is the bug that actually happened. In the simplified model this run shrank it to three steps: open a record that has an attachment → Copy → delete row 1. Nobody had to know in advance that this path needed testing.

Property 3 was not verified at all by the example tests written at the time. The fix does clear the pending-upload list, but no test proved it. If someone deleted that line one day, the original tests would still pass. That is the missing half mentioned above.

"Removing the fix gets caught" is itself a test. It runs the old behaviour with a fixed seed and asserts the property fails; if a property is ever weakened so it stops catching the bug, that test goes red. What it proves is "this set of properties catches this known bug within this test budget", not "any regression will be caught".

Why Not the Alternatives

  • Example tests: Good for fixed, known paths. Trade-off for this problem: only cover sequences someone chose, which is exactly what was missed here; the two complement each other.
  • E2E: Good for confirming the shell really executes the effects. Trade-off for this problem: costlier to run; put large numbers of random sequences at the core layer and use E2E for key integration paths.
  • Recording legacy output and diffing: Good for stateless outputs such as reports and queries. Trade-off for this problem: needs old and new running side by side; stateful multi-step screens are hard to record completely.
  • Formal verification (Quint and similar): Good for concurrent users, transaction ordering. Trade-off for this problem: verifies a design model; whether model and code agree must be checked separately; we plan to use it only for concurrent flows.

Step 3: Extract Rules From the Legacy Code First, Then Check Them Against Existing Data (Agreed, Not Yet Applied)

The Copy case started from knowing what was wrong, then writing properties. Porting a whole system gives you no such head start, so the process is split into five steps, each with a checkable output:

  • ① Extract rules: One rule list per module, with legacy source citations. How it is checked: Citation check, spot-check line numbers.
  • ② Check against data: One verification SQL query per rule. How it is checked: Run on existing data; chase any mismatch.
  • ③ Define the core interface: State / Action / Effect types. How it is checked: Write-point coverage table.
  • ④ Property tests: At least one property per rule. How it is checked: Must be red on base.
  • ⑤ Implementation: The core implementation. How it is checked: Acceptance gate.

Three design choices I find most useful:

Keep rules and properties separate. The rule list records "the rules the old system actually had": one sentence, the legacy file and line number, and a status (holds in the old system / violated by the old system, pending decision / decided to fix). Properties only describe how to test. One rule can map to several properties. Extracting rules and reviewing them go to models from different vendors.

Attach a verification SQL query to each rule and run it on existing data. If you can run read-only queries against existing production data, you can use it to check rules. We already have one example: the code said "records of a certain type are sent to every downstream target once approved", yet the data held a small number of exceptions, because another import path lets the user choose targets. Properties written from the code alone would miss that exception. When data and rule disagree, first rule out a wrong query, data quality and historical data, then have the owner confirm whether it belongs in the rule.

A write-point coverage table. List every place in the legacy module that writes to the database or sends mail; each row must map to an Effect type. The plan is to generate a candidate list by text search, then confirm by hand. Indirect calls and dynamically built SQL won't show up in a search, so the table means "every write point we inventoried has a matching Effect", not "every write point has been found".

To make the AI write in this shape, the plan is to rely on mechanical constraints rather than just prompts: on the backend, architecture tests forbid the core package from importing framework and database layers; on the frontend, stateful screens always use a reducer, and lint rules stop the core from importing API modules. None of this is in place yet, and these constraints only guard dependency boundaries; they don't guarantee the core's logic is correct.

Step 4: Check Whether the Implementing AI Touched the Exam (Built, Two Holes Not Yet Fixed)

The division of labour follows TDD: The integrator (or another model) commits the property tests first. At this point they must be red. The implementing AI changes only the implementation and may not touch the tests. The acceptance gate automatically checks three things: the designated protected files are unchanged between base and head, base is red, and head is green. The gate has been run once on the example.

Reviewing it ourselves turned up two holes, listed here for anyone building something similar:

Protecting only the test files is not enough. An implementer can change the test script in package.json, or a shared test helper, and still turn head green. The protected set should include these by default.

"Red first" needs a reason. The gate currently looks only at the test command's exit code; a failed install or a syntax error also makes it fail, which says nothing about whether the tests can detect anything. It should confirm that base is red because assertions failed.

The properties have a hole too. In the example, properties 1 and 2 decide "same record or not" by record number, while property 3 uses the form's internal sequence id. If the new record happens to be given the same record number as the original and then delete is pressed, property 1 cannot catch it. The fix is to use the internal sequence id throughout (both the attachment rows and the delete effect must carry it), or to state explicitly in the model that record numbers are unique, with a citation to the legacy code.

When It Isn't Worth It

Screens that are mostly data mapping. Query pages, reports and plain CRUD with no decision logic worth verifying separately can skip the core; splitting them out just adds a layer.

Database transaction correctness. For example, two consumers deleting the same row at once: core tests can't cover it. That needs database-level tests, or verifying the design first with a tool like Quint.

Treating it as proof. This is sampling, not proof. Passing only means the generated cases this time didn't violate the properties as written; a weak property passes anyway, as the previous section shows.

For Teams Considering It

Do these first: screens and flows with state transitions, multi-step operations, and failures that delete or send the wrong data. Screens with "new, Copy, edit, delete" in particular are where Copy-style bugs breed.

Where the cost is: the refactoring time to split out a core, one rule list per module, and the access and people needed to run verification queries on existing data. The property tests themselves need no server and can run on every commit.

What actually needs guarding: properties need a source, removing a fix must get caught, and implementers must not be able to touch protected tests.

Disclosure: this article was drafted with help from Claude, an Anthropic model. Claims were checked against our internal method notes and the example code; an independent review by OpenAI Codex was done before publication. A Traditional Chinese version is also available.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.