AI-Assisted Architecture Migration: Keeping Large Refactors Under Control


Greetings, traveler!

A navigation change can touch an iOS app in places that do not look like navigation at all. A push notification opens a detail screen. A coordinator presents authentication before continuing a deep link. A UIKit controller hosts a SwiftUI view whose closure starts another flow. Replace the central router without finding those paths, and the app may still build while some users can no longer reach a screen.

An AI agent can trace references, propose migration steps, update repetitive call sites, and run checks. Its speed is useful only if the team can tell which behavior each change preserves and where the evidence ends. Large refactors therefore need a smaller unit of work than “migrate navigation”: a flow that can be understood, changed, and exercised on its own.

This article uses a hypothetical iOS app with Swift Package Manager modules, UIKit coordinators, and SwiftUI screens. The code is illustrative; adapt it to the app’s existing lifecycle and navigation rules.

Start with the behavior that must survive

Suppose an app has grown several navigation mechanisms: UIKit coordinators manage older flows, while newer features present screens through SwiftUI. The team wants a consistent navigation boundary so features do not need to know how a destination is constructed or which container presents it.

Before choosing an implementation, write down observable behavior. For an account activity flow, that could include:

  • Opening an activity from the account screen pushes the correct detail.
  • A universal link can open the same activity from a cold launch and while the app is running.
  • If authentication is required, the intended destination opens after a successful sign-in.
  • Back navigation, including an interactive swipe, returns to the expected screen.
  • An unavailable or deleted activity produces an appropriate error state.
  • Each scene maintains its own navigation state when the app supports multiple windows.

These statements describe outcomes the migration must preserve. They also expose decisions that an agent cannot safely make from a type signature alone. For example, should opening the same link twice create two detail screens, replace the current one, or do nothing? The current behavior may be accidental, but changing it is still a product decision.

Ask the agent to investigate those flows before editing. Give it the known entry points and request a report with file paths, relevant call sites, unknowns, and proposed checks. Treat its dependency map as a starting point: dynamic registration, generated code, and runtime behavior can be missed by a text search. Run the app and inspect unfamiliar paths with the people who maintain them.

Map the dependency graph before designing the boundary

An architecture diagram drawn from module names alone can hide important coupling. Follow a representative route from the event that triggers it to the screen that appears:

Universal link → link parser → session check → coordinator → screen factory → SwiftUI detail view

Along the way, record which module owns the route, which module constructs the destination, and how identifiers cross the boundary. Include callers outside the feature: notifications, widgets, restoration, shortcuts, and tests. Also inspect error handling and cancellation around asynchronous session checks. A second incoming link while authentication is in progress may reveal assumptions that the happy path does not.

For Swift packages, inspect target dependencies as well as imports. A feature that imports the app module to open a screen creates a different problem from a feature that depends on a small contract module. Moving an interface into a shared package may help, but adding a “core navigation” package for every kind of route can produce a new dependency hub. Keep the first contract limited to the flow being migrated and watch which direction dependencies point.

A useful discovery request is specific about its output:

Trace how an activity detail is opened from the account screen,
from a universal link, and after authentication.

List the relevant files, modules, route parameters, and presentation
owners. Identify existing tests and any behavior you cannot establish
from code. Do not modify files. Suggest the smallest flow that can be
migrated and the checks needed to compare it with the current behavior.

Review the findings before asking for implementation. If the agent cannot determine what happens when a link arrives during sign-in, reproduce the scenario or mark it as an open decision. A guess hidden inside a migration plan becomes an undocumented behavior change.

Introduce a boundary around one flow

Assume the existing account view model calls a concrete coordinator:

@MainActor
final class AccountViewModel {
    private let coordinator: LegacyAccountCoordinator

    init(coordinator: LegacyAccountCoordinator) {
        self.coordinator = coordinator
    }

    func didSelectActivity(id: UUID) {
        coordinator.showActivityDetail(id: id)
    }
}

LegacyAccountCoordinator is an existing application type in this example. The dependency couples the feature to a concrete object even though the view model only needs to request one action. First define that action at a boundary the feature can import:

import Foundation

@MainActor
protocol ActivityOpening: AnyObject {
    func openActivity(id: UUID)
}

Change the view model to accept the protocol and forward the selection:

@MainActor
final class AccountViewModel {
    private let activityOpener: any ActivityOpening

    init(activityOpener: any ActivityOpening) {
        self.activityOpener = activityOpener
    }

    func didSelectActivity(id: UUID) {
        activityOpener.openActivity(id: id)
    }
}

At this point the behavior can still pass through the old implementation. A temporary adapter translates the new contract to the existing method:

@MainActor
final class LegacyActivityAdapter: ActivityOpening {
    private let coordinator: LegacyAccountCoordinator

    init(coordinator: LegacyAccountCoordinator) {
        self.coordinator = coordinator
    }

    func openActivity(id: UUID) {
        coordinator.showActivityDetail(id: id)
    }
}

The account flow’s composition root constructs LegacyActivityAdapter(coordinator: legacyCoordinator) and passes it as the view model’s activityOpener. Build and exercise the flow at this stage. The view model now uses the new interface, while the existing coordinator still handles presentation. Other callers, including deep links, remain on their current paths.

The protocol is deliberately small. If other callers have different presentation requirements, decide whether those requirements belong at this boundary or in a higher-level flow before adding options. In a modular app, place the contract in a module available to both the feature and the implementation; the example omits cross-module public declarations and imports. Introducing a package solely for one method may be unnecessary if an appropriate shared module already exists.

Replace the implementation at the composition root

After the adapter stage is verified, introduce the new presenter. This example uses a UIKit-owned navigation stack and keeps the existing SwiftUI detail screen:

import SwiftUI
import UIKit

@MainActor
final class ActivityCoordinator: ActivityOpening {
    private let navigationController: UINavigationController
    private let makeActivityView: (UUID) -> ActivityDetailView

    init(
        navigationController: UINavigationController,
        makeActivityView: @escaping (UUID) -> ActivityDetailView
    ) {
        self.navigationController = navigationController
        self.makeActivityView = makeActivityView
    }

    func openActivity(id: UUID) {
        let view = makeActivityView(id)
        let controller = UIHostingController(rootView: view)
        navigationController.pushViewController(controller, animated: true)
    }
}

ActivityDetailView is an existing app type. Its factory supplies the dependencies it needs; it must not accidentally recreate the old flow’s business logic or loading state. The snippet covers a single push, not authentication, deep links, duplicate handling, or scene selection.

For the selected account flow, the composition root now injects ActivityCoordinator instead of LegacyActivityAdapter. Both objects satisfy ActivityOpening, so the view model does not need another change. Verify this new path before migrating a second entry point. When the adapter has no callers, remove it. Retire the legacy coordinator only after checking every remaining consumer, including deep links and notifications.

Plan ownership as part of the switch. For example, the scene-level flow owner may retain its navigation controller and active coordinator until the flow ends. If that coordinator strongly retains the navigation controller, and a hosted screen’s view model strongly retains the same coordinator, the objects can form a cycle through the navigation stack. Review the actual object graph and release the flow owner at the appropriate boundary. A separate routing object or a weak reference can be appropriate, but a weak reference needs an independent owner that keeps the coordinator alive for as long as it is needed. The destination factory’s captures need the same review.

Source compatibility alone is not enough. A destination may compile and still open in the wrong scene, appear above a modal, or leave a different back stack. Compare the assembled flow with its recorded behavior, including interactive navigation and deallocation when the flow finishes.

Migrate one vertical slice

A practical first slice is an account screen opening an activity detail. It includes an existing caller, a destination, and a clear user action, but does not require replacing every router in the app. A reasonable sequence is:

  1. Capture current behavior and add missing tests around the chosen flow where they provide useful protection.
  2. Introduce the narrow opening contract and an adapter to the existing coordinator. Build and verify that the current path still works.
  3. Add the new implementation and switch only the selected flow to it. Keep the destination and business logic unchanged unless a separate change is necessary.
  4. Exercise the flow in the running app, review the resulting diff, and record any deviations.
  5. Migrate another entry point only after the team understands the first one. Remove the adapter when no callers use it.

Each stage should leave the app in a usable state. Whether a stage becomes its own pull request depends on the team and on whether the intermediate state is coherent. A temporary adapter is useful only if its removal has an owner and a condition; otherwise it can become permanent indirection.

A feature flag can make a gradual rollout and rollback possible when the two implementations can safely coexist. It is not always appropriate. Navigation state, persisted state, or a partially completed flow may cross the boundary, so switching implementations mid-session can be unsafe. Define when the flag is evaluated and what happens to users already inside the flow. If coexistence is impractical, retain a tested code-level revert and release plan instead of promising an instant rollback.

Keep UIKit and SwiftUI ownership explicit

The example gives one UIKit navigation controller ownership of the selected stack. A SwiftUI NavigationStack can instead own a flow that embeds UIKit content. NavigationStack requires iOS 16 or later, so an app supporting iOS 15 needs a compatible alternative or a different deployment decision. Check navigation bars, safe areas, modal presentation, interactive dismissal, and accessibility when changing containers.

If a SwiftUI path owns a flow, prefer lightweight route values such as identifiers over passing mutable model objects through it. Maintaining a UIKit stack and a SwiftUI path as two independent sources of truth can leave them out of sync after a gesture or programmatic dismissal. If both representations must be maintained, define how changes propagate in each direction and test interactive as well as programmatic transitions.

Give the agent a bounded implementation task

Once the first slice and contract are agreed, give the agent enough context to act without asking it to invent missing policies:

Migrate the account-to-activity-detail flow to ActivityOpening.

Keep the existing detail screen and its loading behavior. The UIKit
navigation controller remains the owner of this stack. Leave existing
deep-link and authentication implementations in place for this slice.
Verify their behavior remains intact. If preserving it requires changes
outside the agreed scope, stop and report the dependency.

Limit changes to the account feature, its composition root, and tests.
Before editing, identify any required change outside that scope.
Run the relevant build and tests, then report commands, results, files
changed, and any behavior that still needs manual verification.

This is a starting instruction, not a universal prompt. If deep links currently call the old coordinator directly, the agent should identify that fact rather than claim that the entire migration is complete. A follow-up task can move that entry point once its authentication and scene behavior are understood.

During review, look for changes that are plausible in isolation but expensive in aggregate: a new router per screen, widened access control, duplicated route definitions, a global navigation singleton, silent error handling, or unrelated cleanup. Also check object lifetimes. A coordinator that disappears too early can break a flow even though the compiler accepts its construction.

Verify each stage against its risks

A build tells you the code compiles for a particular configuration. It does not establish that a push notification opens the correct screen or that an interactive back gesture leaves state consistent. Select checks according to the behavior being changed.

For the activity slice, a small verification matrix might look like this:

AreaExample checkEvidence
ContractSelecting an activity passes its identifier to the openerUnit test with a recording implementation
IntegrationThe selected implementation constructs and presents the intended destinationIntegration test where practical, plus inspection of the running app
Entry pointsA link reaches the destination from a signed-out and a signed-in stateAutomated UI scenario or recorded manual steps and result
NavigationBack button and swipe return to the correct screenUI test or manual check on a simulator or device
BoundariesFeature targets do not acquire unintended app-level dependenciesPackage inspection and diff review
AccessibilityFocus, labels, and Dynamic Type remain usableAccessibility inspection and manual interaction

A recording opener can make the first check inexpensive:

@MainActor
final class RecordingActivityOpener: ActivityOpening {
    private(set) var openedIDs: [UUID] = []

    func openActivity(id: UUID) {
        openedIDs.append(id)
    }
}

A test can inject this object, call didSelectActivity(id:), and assert that the identifier was recorded. That verifies the view model’s handoff, not the actual presentation. A separate integration or UI check is still needed to exercise the assembled flow.

For every reported check, retain the command or procedure, configuration, result, and code revision. If code changes after a relevant check, rerun it on the new state. A failed or unavailable test is an unresolved result, not a pass. If the agent cannot run Xcode or access a physical device, say so in the handoff and assign the missing check to an environment that can.

Measure performance against the migration goal

A navigation refactor can reduce coupling without improving rendering speed. If responsiveness, memory, or launch time is part of the migration’s goal, establish a baseline for those outcomes before implementation. For example, record how long it takes to open the activity detail and inspect the transition for hitches on a representative physical device. Use the same build configuration, OS, dataset, and interaction sequence for the comparison; run it more than once and record the conditions.

Instruments can help explain a regression instead of merely showing that one occurred. Time Profiler can reveal expensive work on the main thread, while Allocations can help investigate memory growth. The detailed SwiftUI instrument in Instruments 26 requires Xcode 26 and a compatible device OS; it can help identify long or frequent SwiftUI updates. Teams on earlier toolchains can use the profiling facilities available to them and should describe what those measurements do and do not cover.

A feed with scrolling hitches deserves a separate investigation. Suppose profiling points to repeated formatting during frequent row updates. The agent can locate that work, propose moving it to a suitable cached or precomputed representation, and explain how the cache stays valid. Repeat the workload after the change. If the measured bottleneck remains and there is a concrete reason to expect a different implementation to help, compare a limited UIKit prototype with the optimized SwiftUI version under equivalent conditions. Include accessibility and maintenance costs in that decision; UIKit is not automatically faster.

A repeatable XCTest performance test can help detect a regression in a specific operation, though it cannot replace an interactive trace. MetricKit offers aggregated field data after deployment. System metric reports cover an earlier period and are delivered at most once per day, so they cannot provide immediate feedback on a single local interaction. Keep diagnostic reports distinct from these daily metric reports.

Decide when to stop migrating

Before expanding the pilot, compare the outcome with the original reasons for the change. Did the slice reduce an identified dependency? Can the team explain where navigation state lives? Did the existing entry points retain their behavior? Is the new code easier to change and review?

If the answer is unclear, stop and adjust the boundary before migrating more callers. It may be cheaper to keep two well-defined approaches than to force every flow through a single abstraction. If the pilot works, use what it revealed to update the next migration task, including known edge cases and checks. Review each subsequent slice on its own merits; a successful first flow is evidence about that flow, not proof that every other flow has the same constraints.

Remove obsolete adapters, flags, and route implementations only after confirming that their callers and rollback requirements are gone. Document the final ownership rules and record any checks that still need attention.