// refactoring

An AI agent that refactors safely.

A codebase with no tests. Inconsistent style. Functions that do five things each. You can spend a month refactoring by hand, or point an agent at it and review its work. The trick is knowing when the agent is right and when it's confidently wrong. Characterization tests pin current behavior first. Staged diffs make every change reviewable. The agent can still get it wrong, so the tests and your review are the safety net.

Prepaid in crypto · no card on file · nothing renews by itself

I. what it does

What you get from the agent.

Characterization tests

Locks down current behavior before any refactor. The agent writes tests that capture exactly how the code works today — bugs and all — so you can change confidently without breaking hidden contracts.

Staged, reviewable diffs

One logical change per diff. Extract a function. Rename a variable. Simplify an error handler. Each change is small enough to review quickly, and revertible if something breaks.

Dead-code detection

Finds functions, variables, and imports that are genuinely unused. But flags edge cases like reflection and metaprogramming where "dead" code is actually alive.

Dependency upgrades

Refactors code to use updated APIs when libraries change. The agent understands deprecations and rewrites code to the new version systematically.

API migrations

Moves code from one API surface to another — e.g., swapping out a library entirely. Staged so you can land the changes incrementally, not as one risky monolith.

Test-gap detection

Identifies functions with zero test coverage and flags them for manual review. You decide if they are critical (need tests) or safe to refactor without them.

II. the real risk

Why legacy code breaks even with good refactoring

Legacy code is full of unspoken contracts. A function looks pointless until you realize it's used via reflection. An exception catch looks paranoid until you see a comment from 2015 saying "this happens in production every other Thursday." A variable looks unused until a runtime debug shows it's set by a third-party library.

An agent reads the code statically. It cannot see these hidden dependencies. It recommends changes confidently that break at 2 AM. That's why you need characterization tests first — they lock down the current behavior, silent contracts and all. Then, when the agent proposes changes, you can see quickly if it broke something.

  • Reflection and metaprogramming — getattr(), setattr(), dynamic imports
  • Public APIs called from outside the repo (the code is not dead, it's export)
  • Race conditions and timing-sensitive code (deletion changes concurrency)
  • Side effects that look unnecessary but are critical (logging, monitoring)

III. the workflow

How to refactor legacy code safely: the complete workflow

Step 1: Characterization tests. Ask the agent to run the current code on sample inputs and capture every output. It generates tests that pin the exact behavior. They should all pass against the current code before you change anything.

Step 2: One focused change at a time. Extract the validation logic into its own function. Rename variables for clarity. Simplify the error handling. One logical change per diff, kept small. Run the tests after each change. If they pass, you keep the diff. If they fail, you revert instantly.

Step 3: Know where to stop. Big architectural changes (splitting modules, swapping APIs entirely) are human decisions. The agent is good at mechanical refactors. Let it do those. You make the calls on strategy.

Step 4: Monitor in production. Log output metrics. If the refactored code behaves differently under real load (slower, more errors, different output), you know immediately. Revert if needed. The staged approach makes rollback fast.

IV. common failure modes

What agents get wrong — and how to catch it

"Dead" code that isn't dead. A function with no internal callers. The agent deletes it. But it's part of the public API, and external code relies on it. The test suite doesn't catch this because there are no internal tests for the public surface.

Reflection and metaprogramming. The agent sees a variable set but never read, and doesn't realize it's set by reflection. Deleting it breaks at runtime.

"Unnecessary" error handling. An exception that hasn't been raised in 5 years of logs. The agent says it's dead code. But it handles the one edge case that happens once a quarter. Deleting it means something fails a few times a year with no safety net.

Silent semantic changes. Reordering operations that look independent. Moving a print statement, removing a temporary variable, inlining a function. Each change looks safe. Cumulatively, they change timing or side effects in ways tests don't catch.

Good characterization tests should catch most of these: the new code produces different output, and you revert. They will not catch everything, which is why review stays on you.

V. questions

Asked before you commit.

How long does a complete legacy refactor take?
It depends on the codebase and how much review you do. Small modules can take an afternoon including review and testing; larger codebases take longer, but you can break the work into independent modules and handle them one at a time.
Can the agent refactor tests themselves?
Yes, but with caution. Old tests often encode behavior that is intentional. The agent can modernize test syntax, remove duplicates, and add missing coverage. But architectural test changes (e.g., switching from mocks to integration tests) should stay human-driven.
What if the characterization tests pass but something still breaks in production?
It means the characterization tests didn't cover the edge case. This is a signal to add more tests, not to stop refactoring. Update the test suite with the production scenario, then re-run the refactor. The staged approach lets you do this incrementally.
How many characterization tests do I need?
Enough to exercise the code paths you care about. A payment processor needs many (valid inputs, missing fields, edge amounts, concurrency); a small utilities module needs far fewer. More is safer.
Can I use this to refactor code I don't understand?
Not well. If you can't read the code, you can't review the diffs, and the refactor becomes a black box. Use the characterization tests to understand the code first, then refactor. Or ask the agent to explain each function before proposing changes.
What happens if the refactor introduces performance regressions?
Benchmark before and after. If latency increases, revert the specific diffs that caused it. The staged approach makes this trivial — you know exactly which change broke it and can discuss alternatives with the agent.
Is this only for bad legacy code?
No. Clean code benefits too. An agent can modernize syntax, apply new language features, remove redundancy, and add missing error handling. The main difference is that clean code requires fewer characterization tests because it has fewer hidden contracts.
Can I integrate this into a CI/CD pipeline?
Partly. The CLI has a non-interactive mode (tartarus run "...") you can script, but we suggest keeping a human in the review step. The characterization tests belong in CI on every change, so regressions are caught before merge.

VI. see also

  1. Uncensored coding agent

    The TartarusAI CLI agent, for refactoring, debugging and feature work.

    Open
  2. Detailed refactoring walkthrough

    A real example: from zero tests to a clean refactor in 10 staged steps.

    Open
  3. TartarusAI vs GitHub Copilot

    How the two compare for multi-file refactors.

    Open

// get started

Point it at your work.

Install the CLI, paste a token, describe the job. Plans start at $20 a month, prepaid in crypto, and nothing renews unless you buy again. There is no free trial.

curl -sSf https://dash.tartarusai.dev/tartarus-setup.sh | bash