Skip to content
Go back

AI-Powered Refactoring

In the previous article, I discussed why refactoring needs to become a continuous practice, especially as AI accelerates software development.

But recognizing the need for continuous refactoring is one thing. Putting it into practice is another.

If I still need to manually inspect the codebase, identify every issue, create cleanup tasks, and ask AI to fix them one by one, I have not fundamentally changed the process. I have only made manual refactoring faster.

The real opportunity is to build a workflow where AI can continuously monitor the codebase, discover improvement opportunities, and take action with minimal human intervention.

So, how can I achieve this?

From AI-Assisted to Automated

Most developers already use AI coding agents to refactor code. They provide a prompt, explain the desired improvement, and let the agent modify the implementation.

This is useful, but it is still reactive. The developer must recognize that something needs improvement and initiate the process.

A more advanced approach is to give AI a continuous responsibility for codebase maintenance.

Instead of waiting for a developer to request refactoring, an automated system can:

  1. Monitor the codebase for potential quality issues.
  2. Analyze changes and identify areas that need improvement.
  3. Evaluate the impact and priority of each issue.
  4. Generate a refactoring plan.
  5. Execute the changes in an isolated environment.
  6. Run automated verification.
  7. Create a pull request for human review.

This introduces a different development model. AI does not just help write and modify code. It also helps maintain the quality of the codebase over time.

A Foundation for Code Analysis

Before AI can improve a codebase automatically, it needs a way to understand its current state.

I cannot simply ask an AI agent to make the code better without defining what better means.

A practical approach is to combine two types of feedback, deterministic analysis and AI-based analysis.

Static Analysis Tools

These are measurable signals produced by tools with predictable results.

Examples include:

CategoryTools / MetricsWhat to detect
Code complexityESLint, SonarQubeComplex functions, excessive branching, code smells
Duplicationjscpd, SonarQubeRepeated code blocks
Dependenciesdependency-cruiser, MadgeCircular dependencies, incorrect dependency directions
Test qualityCoverage, mutation testingUntested code and weak regression tests
Type safetyTypeScript, type checkingType errors and unsafe patterns
SecuritySemgrep, CodeQLVulnerabilities and insecure implementations
Dependenciesnpm audit, dependency reportsVulnerable, outdated, or unnecessary packages

These tools provide objective evidence about the codebase.

For example, a static analysis tool might identify a function with high cyclomatic complexity, while a dependency analyzer might detect circular dependencies between modules.

However, metrics alone cannot determine whether a particular design is actually problematic.

A large module is not necessarily a bad module. Some duplication may be intentional. A function with many branches might represent legitimate business rules.

This is where AI becomes valuable.

AI for Code Context

AI can interpret the signals produced by deterministic tools alongside the actual implementation and architectural context.

It can investigate questions such as:

  • Is this duplication worth consolidating?
  • Are these responsibilities incorrectly placed?
  • Does this abstraction introduce unnecessary complexity?
  • Are multiple modules implementing the same business rules differently?
  • Is the current dependency structure making future changes harder?
  • Which parts of the codebase are likely to become maintenance bottlenecks?

For example, a dependency analyzer might report that a module has many incoming and outgoing dependencies.

A traditional tool reports the structure. AI can investigate the actual responsibilities of that module, understand why other components depend on it, and propose alternative designs.

The distinction is important:

Deterministic tools tell me what is happening. AI helps me understand why it matters and what I should do about it.

The Automated Workflow

Once I have quality signals, I can build an automated workflow around them.

A useful architecture consists of several stages.

Detecting Issues

The first responsibility is to identify potential improvements without waiting for developers to report them.

There are several ways to trigger this process:

On code changes

Whenever a pull request is opened or updated, analyze the changed files and their immediate dependencies.

This helps catch problems introduced by new implementations before they become part of the main codebase.

On a schedule

Run broader analysis periodically, such as nightly or weekly.

This is useful for detecting problems that accumulate across multiple changes:

  • Increasing complexity.
  • Growing code duplication.
  • Architectural inconsistencies.
  • Unused abstractions.
  • Outdated dependencies.
  • Repeated implementation patterns.

On demand

Developers can also trigger an analysis when investigating a particular module or preparing a larger change.

Combining these triggers provides both immediate feedback and a broader view of codebase health.

Analyzing Impact

Raw analysis results are not yet actionable refactoring tasks.

An AI agent should investigate each finding before recommending a change.

For example, imagine a report identifies three services with similar validation and error-handling logic.

Rather than immediately merging them into a shared utility, the agent should:

  1. Inspect the implementations.
  2. Compare their responsibilities and differences.
  3. Trace their callers and dependencies.
  4. Check existing tests.
  5. Determine whether the duplication is accidental or intentional.
  6. Explain the potential benefits and risks of consolidation.

The output should be a structured finding containing:

  • Problem description.
  • Affected files and components.
  • Evidence supporting the finding.
  • Potential impact.
  • Suggested improvement.
  • Estimated effort and risk.

This step prevents AI from treating every detected issue as an instruction to rewrite code.

Prioritizing

An automated system can easily generate hundreds of potential improvements.

Fixing everything is neither practical nor desirable.

Instead, AI should prioritize issues based on their actual maintenance impact.

Some useful considerations include:

FactorQuestion
Change frequencyIs this code frequently modified?
ComplexityDoes it make future changes difficult?
CouplingDoes it affect multiple components?
DuplicationDoes the same logic need to be maintained in multiple places?
RiskCould the current implementation introduce defects?
EffortHow much work is required to improve it?

For example, reducing complexity in a frequently modified business-critical service may provide more value than cleaning up an isolated utility that rarely changes.

The goal is to maximize long-term maintenance value rather than maximize the number of issues fixed.

Planning and Executing

After selecting an improvement, the agent creates a concrete implementation plan.

A good plan should define:

  • What needs to change.
  • Why the change is necessary.
  • Which files are affected.
  • Which existing behaviors must remain unchanged.
  • What tests are required.
  • How success will be evaluated.

The agent then executes the refactoring in an isolated branch or worktree.

For larger improvements, the work should be divided into smaller changes.

For example, extracting shared business logic might involve:

  1. Identifying the common behavior.
  2. Creating a shared implementation.
  3. Migrating one consumer.
  4. Running regression tests.
  5. Migrating the remaining consumers.
  6. Removing obsolete implementations.

Each step should be independently verifiable.

This makes the changes easier to review and reduces the risk of large, uncontrolled modifications.

Verifying Changes

One of the most important requirements is that AI must verify its own changes.

A successful refactoring should improve the internal structure without unintentionally changing external behavior.

The agent should run:

  • Unit and integration tests.
  • Type checking.
  • Linting and formatting.
  • Relevant regression tests.
  • Static analysis and architectural checks.

For critical code, additional verification such as mutation testing or targeted end-to-end tests may be appropriate.

If verification fails, the agent can investigate the failure and attempt a correction within a predefined retry limit.

If it cannot resolve the issue confidently, it should stop and report the problem rather than continue modifying unrelated code.

Delivering Through Pull Requests

Once the changes pass verification, the agent creates a pull request.

The PR should explain:

  • What problem was identified.
  • Why it matters.
  • What was changed.
  • How the implementation improves maintainability.
  • Which tests and checks were executed.
  • Any remaining risks or limitations.

Developers can then review the changes and decide whether to merge them.

This creates a practical separation of responsibilities:

AI continuously discovers and proposes improvements. Developers retain control over important engineering decisions.

Fitting into the Lifecycle

The workflow above does not need to run as one large autonomous process.

It can be integrated into existing development workflows at different levels.

During Development

Coding agents can receive immediate feedback from quality tools.

Whenever they modify code, they can check whether the changes introduce:

  • New duplication.
  • Increased complexity.
  • Architectural rule violations.
  • Unnecessary dependencies.
  • Missing regression coverage.

This is particularly useful because problems can be addressed while the relevant context is still available.

During Pull Request Review

AI can act as an additional reviewer focused specifically on maintainability.

Rather than reviewing only functional correctness, it can compare the changes against the existing architecture and identify potential long-term maintenance problems.

For example:

  • Did the new implementation duplicate existing logic?
  • Did it introduce a new dependency direction?
  • Did it create another abstraction unnecessarily?
  • Did the change increase the number of files required for a simple future modification?

The objective is to prevent new technical debt from entering the codebase.

Scheduled Maintenance

A separate maintenance agent can periodically inspect the broader codebase.

It can review accumulated findings, identify recurring patterns, and propose improvements that are not necessarily related to recent feature work.

This is particularly valuable for older modules that are rarely touched but still represent architectural or maintenance risks.

Importantly, scheduled maintenance should not automatically rewrite the entire codebase. It should generate a manageable set of high-value improvements.

Levels of Autonomy

Once the basic workflow is established, I can gradually increase the level of automation.

Not every refactoring task requires the same level of human involvement.

A practical model could have three levels.

Level 1 – Assisted

AI identifies problems and proposes improvements. Developers decide what to change and perform or supervise the implementation.

This is a good starting point for existing codebases with limited automated verification.

Level 2 – Supervised Automation

AI independently analyzes issues, implements changes, runs tests, and creates pull requests.

Developers review and approve every change before merging.

This is likely the most practical approach for many production systems.

Level 3 – Bounded Autonomy

AI can automatically merge or apply narrowly scoped changes when they satisfy predefined conditions.

For example:

  • Formatting and mechanical cleanup.
  • Removing confirmed unused imports.
  • Applying deterministic code transformations.
  • Updating low-risk generated artifacts.

More complex changes involving business logic, public APIs, data models, or architectural boundaries should still require human approval.

The important principle is to increase autonomy based on the reliability of the verification process, not simply the capabilities of the model.

System Architecture

I can implement this approach using existing development infrastructure without necessarily building a completely new platform.

A possible architecture:

Inputs

  • Git repository and commit history.
  • CI/CD results.
  • Static analysis reports.
  • Test and coverage reports.
  • Dependency and architecture reports.

Analysis

  • Scripts and analysis tools collect objective signals.
  • AI agents investigate findings and understand their context.
  • A prioritization process selects valuable improvements.

Execution

  • An isolated coding agent receives a specific task.
  • The agent creates a plan and modifies the code.
  • Automated checks provide feedback.
  • The agent corrects issues within predefined limits.

Delivery

  • The agent creates a pull request.
  • CI runs independently.
  • Developers review and approve the changes.
  • Results are tracked for future analysis.

This can be implemented with familiar tools:

ComponentPossible implementation
Source controlGitHub
Triggers and orchestrationGitHub Actions, scheduled workflows
Static analysisESLint, SonarQube, Semgrep
Dependency analysisdependency-cruiser, Madge
Test verificationVitest, Jest, Playwright
Coding agentClaude Code, Codex, Cursor, and other coding agents
IsolationGit worktrees, containers
DeliveryAutomated GitHub Pull Requests

The specific tools are interchangeable. What matters is the workflow and the feedback loop connecting them.

Conclusion

AI gives us an opportunity to rethink how software maintenance works.

Instead of relying on developers to periodically identify and schedule refactoring, we can build systems that continuously monitor code quality, investigate potential problems, and proactively propose improvements.

The most important shift is from asking AI to refactor code to giving AI an ongoing responsibility for maintaining the codebase.

However, automation alone does not guarantee better software. It needs clear engineering principles, reliable verification, controlled execution, and human oversight.

The ultimate goal is not to build an AI that constantly rewrites our code. It is to build a development workflow where code quality is continuously monitored and improved as naturally as code is written.

Previous Post
Next Post