跪拜 Guibai
← Back to the summary

Refactoring with Codex: A Batch-by-Batch Workflow That Preserves Business Contracts

How to Use Codex for a Reliable Project Refactoring: Methods, Rhythm, and Reusable Prompts

Many people, when letting AI participate in refactoring for the first time, are used to compressing the requirement into a single sentence: "Help me refactor this project."

This sentence can certainly start a conversation, but it is difficult to start a reliable engineering collaboration. Because true refactoring is often not "rewriting the code in a different way," but rather migrating an old system into a new structure without breaking business rules, connecting historical logic back to the current project, and unifying scattered implementations into maintainable patterns.

In such tasks, the place where AI is most prone to problems is not that it cannot write code, but that it starts writing code too quickly. It might guess business meaning based on file names, change interfaces based on template experience, and judge global rules based on partial pages, ultimately producing a result that "looks like it can run, but key contracts have already changed."

I recommend treating Codex as an engineering collaborator, not a code generator. Let it read first, ask first, design first, then modify in batches and verify in batches. This way, AI's speed becomes an advantage, not a risk amplifier.

1. First, Change the Task from "Writing Code" to "Building a Chain of Evidence"

The first step in project refactoring is not to let Codex modify files, but to let it read the sources of facts clearly.

There are usually at least four types of information that need to be prioritized:

These sources often conflict. The target project's style might be more modern, but the source project's business rules are more real; the reference implementation might look better, but it might also carry assumptions from another system. Without prioritization, Codex can only make judgments for you.

So the most important prompt at the start is not "start refactoring," but requiring it to establish context first.

Please first read the current project, source project, interface documentation, and reference materials, and organize the context before refactoring.

Please focus on outputting:
1. The current project's tech stack, directory structure, common components, state management, routing, and request encapsulation.
2. The business rules, fields, interface contracts, permission logic, and key interactions in the source project that need to be preserved.
3. The data structures, authentication methods, error handling, and pagination methods in the interface documentation that affect the global design.
4. The parts of the reference implementation that can be reused, and the assumptions that cannot be directly copied.
5. The risk points in this refactoring that are most prone to errors.

Do not modify any files before completing this step.

The role of this prompt is to switch Codex from an "executor" to an "investigator." It needs to prove it has seen the context before starting to design a plan.

2. Set Confirmation Gates for High-Risk Decisions

During refactoring, there are some issues that AI cannot be allowed to decide on its own, for example:

Once these points go wrong, dozens of files that follow will also go wrong. The best practice is to require Codex to stop at these points, provide options, and wait for your confirmation.

The following content belongs to global contracts: login authentication, permission model, navigation source, pagination protocol, interface error handling, whether backend fields are changed.

When encountering these issues, please stop coding first and provide 2-3 alternative solutions:
- The implementation method for each solution
- The impact on the frontend, backend, data, and historical functionality
- Risks and maintenance costs
- Your recommended solution and reasoning

Wait for my confirmation before proceeding to the design document or code modification.

This "confirmation gate" is very important. It is not about reducing efficiency, but about preventing AI from making business decisions for you at critical points.

3. Write the Design Document First, Then Write Code

In large-scale refactoring, the design document is not formalism. Its value lies in fixing the boundaries.

A sufficiently good refactoring design document should answer these questions:

You can ask Codex like this:

Please write a refactoring design document based on the confirmed plan.

The document needs to cover:
1. Refactoring goals and non-goals
2. Information source priority
3. Overall architecture and migration boundaries
4. Global designs such as login authentication, permission model, navigation source, pagination protocol, interface error handling
5. Page or module migration principles
6. Reuse boundaries for the reference implementation
7. Risk list and verification methods
8. Phased implementation suggestions

Please write only the design document first, do not modify business code. After writing, self-check for placeholder content, contradictions, unresolved issues, or scope drift.

After the design document is approved, let Codex write the implementation plan.

The design document has been confirmed. Please write the first phase implementation plan.

Requirements:
1. Break the task into small batches that can be independently verified
2. For each batch, explain the scope to be modified, expected results, and verification method
3. Prioritize establishing the global adaptation layer, then migrate business pages or functional modules
4. Do not migrate all pages at once
5. After each batch is modified, explain the verified items, unverified items, and remaining risks

This step can change refactoring from "large and scattered" to "small and stable."

4. Build the Foundation First, Then Move the Business

Many project refactorings fail because they start by moving pages or modules. As more and more pages are moved, they realize that request protocols are inconsistent, permission judgments are inconsistent, data structures are inconsistent, and routing rules are inconsistent.

A more stable order is to build the foundation first:

  1. Request encapsulation and error handling
  2. Login and authentication state
  3. Permission and navigation adaptation
  4. Pagination or list data protocol
  5. Common component patterns like modals, details, tables, forms
  6. One low-risk page or module as a template

The prompt can be written like this:

Please complete the refactoring foundation first, do not rush to migrate all business modules.

The first batch only handles:
1. Request encapsulation and error handling adaptation
2. Login authentication state integration
3. Permission and navigation data adaptation
4. Pagination or list protocol adaptation
5. One low-risk page as a template

Requirements:
- Maintain the current project's code style and component patterns
- Do not change confirmed business contracts
- Do not incidentally refactor unrelated code
- Run the project's existing checks after completing each small batch
- When reporting, explain the modification scope, verification results, and remaining risks

This type of prompt allows Codex to separate "infrastructure" from "business migration," reducing rework.

5. When Migrating Modules, Require It to Align Three Things Simultaneously

Every time a module is migrated, three lines must be looked at simultaneously:

Aligning only one of them is not enough. A page that looks like the new system but has wrong business fields is not acceptable; fields that are correct but the interaction style is like the old system is also not acceptable; the interface can be called, but permissions and states are not aligned, still not acceptable.

You can give Codex a module migration prompt like this:

Please migrate [Module Name] to the current project.

Migration requirements:
1. First read the implementation of similar modules in the current project, reuse existing components, state management, request encapsulation, and style rules
2. Then read the pages, fields, operations, permission judgments, and boundary logic of this module in the source project
3. Confirm request parameters, return structures, error handling, and pagination methods based on the interface documentation or data contract
4. Page experience leans towards the current project, business rules lean towards the source project, data contract leans towards the interface documentation
5. Do not introduce unconfirmed new dependencies
6. Do not modify unrelated modules
7. After completion, run the project's existing checks and provide a difference comparison result

If the module is relatively complex, you can add one more sentence:

If you find conflicts between the current project pattern, source project logic, and interface documentation, please stop first and explain the conflict, do not choose on your own.

This sentence can prevent AI from overwriting real business rules with an implementation that "looks reasonable."

6. User Feedback Must Become the Next Round of Constraints

When using Codex for refactoring, user feedback is not an interruption, but a calibration.

For example, you find:

Don't just say "this is wrong," it's better to turn the feedback into new constraints.

Please correct the previous round's implementation according to the following constraints:

1. [Specific behavior] must be consistent with the source project
2. [An assumption in a reference implementation] does not apply to the current project, do not adopt it
3. [An entry point or process] needs to retain historical behavior
4. This round only fixes these issues, do not expand the modification scope

Please re-read the relevant current implementation and source project implementation first, then modify. After fixing, explain which parts have been aligned and which parts still need real environment verification.

This way of writing allows Codex to deposit feedback into the current task, rather than just doing superficial patching.

7. Difference Review is More Important Than "I'm Done"

The most feared thing in large-scale refactoring is the phrase "it's done." What is truly valuable is the difference review.

You can ask Codex to do a round of review after migration:

Please perform a difference review of the current refactoring results against the source project, do not modify code first.

Review scope:
1. List fields and query conditions
2. Operation flows such as add, edit, delete, review, submit
3. Detail page or detail modal
4. Permission judgments and button display
5. Data refresh logic
6. Interface parameters and return data usage
7. Error handling and empty states
8. Consistency with the current project's common component patterns

Output format:
1. Confirmed differences: Explain the current behavior, source project behavior, impact scope, and suggested fix method
2. Parts that have been checked and no obvious differences found
3. Uncertain parts or parts that need my confirmation

Please draw conclusions only based on files, interface documentation, or running results. Inferred content must be marked as inference.

This prompt can force Codex to speak with evidence. It will move from a "sense of completion" back to a "verifiable state."

8. Verification Must Be Layered, Not Just Looking at Build Passing

Build passing only proves the code can compile, not that the business is aligned.

A relatively complete verification should include:

You can prompt like this:

Please perform layered verification for this round of refactoring.

At least check:
1. The project's existing lint, type checking, or formatting checks
2. Project build
3. Whether the entries or pages involved in this round are reachable
4. Whether request parameters, response parsing, pagination, and error handling conform to the interface contract
5. Differences from the key business rules of the source project
6. Whether there are unrelated file changes

Finally, report in three categories:
- Completed and verified
- Completed but can only be statically verified
- Unverified or needs real environment verification

This is much more reliable than simply asking to "run build."

9. Deposit Experience into Project Rules

If a project will be maintained long-term, after refactoring, don't just leave code, but also leave rules.

These rules can be project documentation, development conventions, or local skills or prompt templates that Codex can read. Content can include:

The prompt can be written like this:

Please deposit the experience from this refactoring into maintenance rules for the current project.

Requirements:
1. Summarize only based on the confirmed implementations of the current project
2. Do not include sensitive paths, real interfaces, accounts, domain names, or private business information
3. Cover page development, interface adaptation, permission navigation, verification processes, and difference review
4. Write as rules that subsequent Codex or developers can directly read and execute
5. Add a self-check checklist to prevent subsequent modifications from deviating from the current project pattern

This step can turn a one-time collaboration experience into the starting point for the next one.

10. A Complete Set of Prompts That Can Be Directly Reused

The following can serve as the starting prompt for any project refactoring. Just replace the content in square brackets with your project name, path, or description.

I want to use Codex to assist in completing a project refactoring.

Project relationships:
- Current project: [Target project description], this is the final project to be implemented
- Source project or old implementation: [Source project description], this is an important source of business rules and historical behavior
- Interface or data contract: [Interface documentation, data structures, protocol description]
- Reference materials: [Reference projects, design drafts, historical documents, etc., optional]

Overall goals:
- Retain the current project's tech stack, engineering style, directory organization, common components, and verification methods
- Retain the confirmed business rules, field meanings, permission logic, and key interactions from the source project
- Use the interface or data contract as the standard for handling request parameters, response structures, error handling, pagination, and authentication
- Reference materials can only be used as reference, cannot override confirmed business contracts

Working method:
1. First read the current project, source project, interface or data contract, reference materials, organize context and risks, do not modify code first
2. For global issues such as login authentication, permission model, navigation source, pagination protocol, error handling, whether backend fields are changed, provide solutions first and wait for my confirmation
3. After the solution is confirmed, write the refactoring design document first, then write the phased implementation plan
4. Establish the global adaptation layer first, then migrate specific modules
5. Only do one verifiable small batch at a time, do not make large-scale changes all at once
6. After each batch is modified, run the project's existing checks and perform a business difference comparison
7. When reporting, explain the modification scope, evidence sources, verification results, unverified risks, and whether there are unrelated changes

Constraints:
- Do not guess business rules based on experience
- Do not directly bring assumptions from reference materials into the current project
- Do not incidentally refactor unrelated code
- Do not expose sensitive paths, real interfaces, accounts, domain names, or private business data
- If there are conflicts between the current project, source project, and interface contract, explain the conflict first and wait for confirmation

11. Prompts for Several High-Frequency Scenarios

1. Context Reconnaissance

Please first perform a context reconnaissance before refactoring, do not modify files.

Please output:
1. The current project's tech stack, directory structure, key dependencies, and common development patterns
2. The business modules, key processes, and boundary logic in the source project that need to be preserved
3. The rules in the interface or data contract that affect the global design
4. The parts of the reference materials that can be reused and those that cannot be directly reused
5. The main risks of this refactoring and issues that need my confirmation

2. Solution Confirmation

Please only analyze the solution for [Global Issue Name], do not modify code.

Please provide 2-3 solutions, and explain for each:
1. Implementation method
2. Scope of modification
3. Impact on historical business
4. Impact on subsequent maintenance
5. Risks
6. Recommended solution

Wait for my confirmation before continuing.

3. Batch Implementation

Please implement this batch according to the confirmed design.

This batch's goal: [Clearly write this batch's goal]

Requirements:
1. First read the relevant current implementation, source implementation, and interface contract
2. Only modify the necessary files for this batch
3. Follow the current project's existing patterns
4. Retain confirmed business contracts
5. Run the project's existing checks after modification
6. Report the modification content, verification results, and remaining risks

4. Module Migration

Please migrate [Module Name].

Requirements:
1. UI, interaction, and code organization follow the current project's patterns
2. Fields, business processes, and permission rules align with the source project
3. Request parameters, response parsing, and error handling align with the interface contract
4. If conflicts are found among the three, stop first and explain the conflict
5. Do not introduce unconfirmed new dependencies
6. Do not modify unrelated modules
7. After completion, perform a difference check and project check

5. Difference Review

Please perform a difference review for [Module Name or This Round's Changes], do not modify code first.

Please check:
1. Page display
2. Query conditions
3. Form fields
4. Action buttons
5. Permission judgments
6. Detail display
7. Data refresh
8. Interface parameter and response usage
9. Error handling

Please output confirmed differences, parts checked with no obvious differences, and parts needing my confirmation.

6. Targeted Fix

Please only fix the following confirmed differences:

1. [Difference One]
2. [Difference Two]

Requirements:
1. First read the current implementation and source implementation
2. Only modify relevant files
3. Do not expand the modification scope
4. Maintain the current project's style
5. Run necessary checks after fixing
6. When reporting, distinguish between this round's changes and existing unrelated changes

7. Verification Closure

Please perform closure verification for this round of changes.

Please check:
1. The project's existing lint, type checking, tests, or build commands
2. Whether the pages or entries involved in this round are reachable
3. Whether the data contract is aligned
4. Whether key business rules are aligned
5. Whether there are unrelated file changes

Finally output:
- Verified and passed
- Could not be verified and the reason
- Remaining risks
- Suggested next steps

12. Conclusion

When Codex participates in refactoring, what truly determines the quality of the result is not a single magical prompt, but the entire collaboration rhythm.

Read the evidence first, then confirm the plan; build the foundation first, then move the business; modify in small batches first, then verify in layers; do a difference review first, then declare completion.

When you use Codex in this way, it is no longer just a tool that "helps you write code," but becomes a collaborator that can participate in engineering judgment, execute migration, discover differences, and deposit rules.

This is where AI is most worth using in real project refactoring.