Four-Stage Workflow for Building Complex Features with AI Coding Tools
A reliable AI-assisted development process requires more than generating code from a prompt. This article presents a four-stage workflow—research, planning, implementation, and verification—for managing complex features involving multiple modules, data consistency, permissions, concurrency, and failure recovery. It also explains how to structure context, preserve evidence, define stage gates, and create effective handoffs so that AI coding tools remain aligned with business constraints and engineering requirements.
1. Why Complex Features Often Have to Be Rebuilt Halfway Through
When using an AI coding tool to build a simple feature, a clear requirement combined with relevant code is often enough to produce a usable implementation. However, this approach becomes unreliable when a task involves multiple modules, data consistency, authorization, concurrency, or failure recovery.
Consider adding inventory reservation to an order system. At first glance, the feature may seem to require only one additional inventory check. In practice, it raises several questions:
- What state should an order enter when inventory is insufficient?
- If a user submits the same request repeatedly, will available inventory be deducted more than once?
- How should reserved inventory be released after an order is canceled?
- How can the system prevent overselling when multiple requests try to purchase the last item at the same time?
- What happens if inventory reservation succeeds but saving the order fails?
If these questions are not clarified before implementation, the tool must fill in the gaps with assumptions. The generated code may be locally valid while conflicting with actual business constraints.
Rework is therefore not only a code-generation quality problem. It usually means that constraints were lost at three points: the requirements did not define a clear boundary, the design was not reviewed, or the implementation was not covered by a complete verification loop.
A mature workflow should always make clear:
- What is being solved now;
- What evidence supports the decision;
- What must not be changed; and
- How completion will be demonstrated.
2. Context Management: More Information Does Not Always Produce Better Results
Distinguish Limited Capacity from Mixed Information
Context is the set of information currently available to the model. It may include task requirements, project constraints, file contents, conversation history, tool results, and intermediate analysis.
The context window has a capacity limit, but context quality can degrade long before that limit is reached. Even when sufficient space remains, the following information can interfere with reasoning:
- An old proposal that was rejected but not clearly marked as obsolete;
- Large amounts of source code unrelated to the current feature;
- Repeated requirement descriptions with subtle differences;
- Excessively long logs and outdated error messages;
- Conclusions with no source and business assumptions that have not been confirmed.
The goal is not simply to reduce input length. It is to improve relevance, consistency, and traceability.
Do Not Treat a Fixed Utilization Ratio as a Universal Rule
A context-utilization ratio can be useful as a team reminder, but it should not be treated as a universal boundary for model performance. There is no single percentage at which every model, tool, task, or session will suddenly fail.
Different tools may count context differently. They may also use different system instructions, history-compression mechanisms, and output-reservation strategies. The same utilization ratio can therefore represent different amounts of usable space.
A more reliable approach is to:
- Check usage after reading large files or switching stages when the tool supports usage monitoring;
- Reserve space for later analysis, code changes, and verification results;
- Organize the current state when the tool repeatedly forgets constraints, refers to rejected approaches, or rereads the same material;
- Adjust reminder thresholds based on actual task experience rather than applying a fixed number mechanically.
Divide Context into Three Layers
Stable constraints contain information that remains valid over time, such as directory structure, coding standards, test procedures, and security boundaries. This layer should be short and explicit and should not contain temporary logs.
Task facts contain the current feature goal, code evidence, design decisions, and unresolved questions. This layer should be updated as research progresses.
Temporary execution details contain the current changes, errors, and debugging results. Once an issue is resolved, retain only the final conclusion and necessary evidence instead of carrying the entire process forward.
This separation prevents project rules from being mixed with one-time debugging information and makes it easier to resume work in a new session.
3. Establish a Four-Stage Process with Explicit Gates
Complex features should be divided into four stages: research, planning, implementation, and verification. Each stage must produce a clear artifact rather than relying only on scattered conclusions in a chat history.
| Stage | Core question | Main artifacts | Condition for moving forward |
|---|---|---|---|
| Research | How does the existing system work? | Current-state report, evidence, and open questions | Key call paths and constraints are understood |
| Planning | How should the system be changed? | Design, task breakdown, and acceptance criteria | High-risk decisions are confirmed |
| Implementation | How can the smallest reliable change be delivered? | Code, tests, and change records | Planned changes are complete and local checks pass |
| Verification | What evidence proves the change is correct? | Test results, risk list, and delivery notes | Acceptance items are complete or explicitly marked as blocked |
A stage transition does not require mechanically deleting all previous history. A better principle is to save the handoff artifacts first, then open a new session or reorganize the context when necessary. Otherwise, cleanup may remove the reasoning behind important design decisions.
The artifacts can be stored in ordinary text files:
task-materials/requirements.mdcurrent-state-research.mdimplementation-plan.mdverification-record.mdhandoff-summary.md
These are ordinary documents and do not require special commands. Sensitive configuration, credentials, and real user data should not be stored in them.
4. Research Stage: Collect Facts Before Proposing Solutions
Read Code Based on the Problem
The goal of research is not to browse the entire repository. It is to answer the questions relevant to the feature.
For inventory reservation, the investigation might follow this path:
- Find the order-creation entry point and its parameter-validation logic.
- Trace how the order service accesses inventory data.
- Confirm the current transaction boundaries and concurrency-control mechanisms.
- Find the paths for order cancellation, timeout closure, and failure recovery.
- Read related tests to understand the behavior the system already promises.
Start with entry points, call relationships, and relevant tests. Read additional files only when the investigation reveals a gap instead of loading the entire project at once.
Parallel Research Requires Explicit Responsibilities
If the tool supports parallel tasks, research can be divided into interface flows, data constraints, test coverage, and failure recovery. If it does not, complete the same work sequentially.
Parallel execution does not automatically produce correct results. Each research task should have a limited scope, read-only access to files, and a consistent report format. Multiple execution units should not modify shared code at the same time.
The conclusions must eventually be combined and checked for conflicts. For example, one investigation may conclude that inventory updates are protected by a transaction, while another may find that order persistence occurs outside that transaction. Such a contradiction must be investigated rather than simply merged into the report.
Preserve Verifiable Evidence
A research report should include at least:
- Confirmed facts and their code locations;
- Important call paths and data flows;
- Constraints and defects in the current implementation;
- Inferences that have not yet been verified;
- Questions that require a decision from the requirements owner.
Code references may use a format such as:
Conclusion: The current inventory update does not check the number of affected records.Evidence: src/stock/reservation.ext:84-103Impact: The caller may treat the operation as successful even when no update occurred.To confirm: Check whether an upper-level compensation or retry mechanism already exists.
File names and line numbers must come from actual inspection. They should never be invented. Because line numbers may change after edits, also record the function name or another stable identifier to make the location easier to find again.
5. Planning Stage: Turn Goals into a Verifiable Design
Define Both Goals and Non-Goals
“Support inventory reservation” is still too broad. A more useful definition might be:
- Attempt to reserve inventory before creating an order;
- Ensure repeated calls for the same business request do not increase the reservation more than once;
- Release the reservation when the order is canceled;
- Return an explicit failure result when inventory is insufficient;
- Do not redesign the entire inventory-accounting system in this task.
Non-goals prevent the tool from expanding the scope automatically and turning a feature implementation into an unrelated repository-wide cleanup.
Define Business Invariants First
Business invariants are conditions that must hold across every execution path. For example:
Available inventory must never be less than zero.The same reservation request may create at most one effective reservation.The same reservation may be released at most once.A failed reservation must not be interpreted as successful order creation.
Invariants are more important than simply “adding a handler” because they directly determine the concurrency strategy, idempotency behavior, and test design.
Describe the Consistency Strategy Before Coding
When orders and inventory use the same transactional resource, evaluate whether a local transaction can guarantee consistency for the related writes.
When an operation crosses multiple independent systems, do not assume that one ordinary transaction can cover the entire workflow. Based on the existing architecture, evaluate mechanisms such as state machines, retries, compensation, and message delivery. Define how intermediate failure states will be identified and recovered.
The plan does not need to choose the most complicated solution. It must explain its assumptions, failure behavior, and remaining risks. If a critical decision is still unresolved, pause the related implementation instead of allowing the tool to guess.
Break the Plan into Independently Verifiable Steps
An executable plan might be:
- Add baseline tests for current behavior.
- Define reservation results and failure semantics.
- Implement a conditional inventory update.
- Add duplicate-request detection.
- Integrate the reservation into order creation.
- Add the release path.
- Verify concurrency, failure handling, and compatibility.
Each step should identify the relevant files, expected behavior, and verification method. If the change requires a data-structure migration, also consider historical data, the compatibility window during rollout, and rollback limitations.
6. Implementation Stage: Make Small Changes and Detect Deviations Early
Handle One Clear Objective per Iteration
A general task instruction can be written as follows:
Complete only the current step in the implementation plan.First read the specified files and related tests to confirm existing constraints.Do not perform unrelated renaming, formatting, or public-interface changes.If the plan conflicts with the actual code, explain the evidence and pause the related change.After completion, list the changes made, checks performed, and unresolved issues.
This constrains the tool from freely generating an entire feature and turns it into an executor of a reviewable change.
Test Alongside Implementation
Run relevant checks after completing each behavioral unit rather than waiting until the end. For inventory reservation, tests should cover at least:
- Reservation succeeds when inventory is sufficient;
- Reservation fails without changing data when inventory is insufficient;
- Repeated requests do not create additional reservations;
- Repeated releases do not increase available inventory more than once;
- Concurrent requests do not violate the inventory constraint;
- A downstream failure produces the expected recovery state.
Concurrency tests must match the actual data-access mechanism. Verifying method calls with mock objects alone is usually insufficient to prove concurrency safety in a real storage environment.
Control the Change Scope and Execution Permissions
Use an isolated workspace or change branch to avoid overwriting unsaved manual work. Deleting files, changing permissions, and running data migrations should require separate confirmation.
When an unplanned issue appears, distinguish between:
- A necessary fix that blocks the correctness of the current feature;
- An unrelated historical problem.
Handle the first after updating the plan. Record the second as a separate issue so that the scope does not continue expanding.
7. Verification Stage: Confirm Completion with Independent Evidence
Verification should not ask only whether the code has been written. It should answer, item by item, whether the acceptance criteria have been proven.
At minimum, check five areas:
- Change review: Confirm that there are no unrelated files, sensitive information, or missing configuration changes.
- Static checks: Run the project’s existing syntax, type, and code-quality checks.
- Behavioral tests: Cover normal, boundary, failure, and repeated operations.
- Integration validation: Confirm actual behavior with storage, transactions, and external dependencies.
- Delivery review: Document release order, monitoring indicators, rollback procedures, and known limitations.
The verification record should distinguish facts from future plans:
Check: An order is not created successfully when inventory is insufficient.Result: Passed.Evidence: The relevant integration test completed successfully.Check: No excessive reservation occurs under high concurrency.Result: Not yet verified.Reason: The current environment lacks the required validation conditions.Next step: Add a concurrency test in an isolated environment.
A test that was not run must not be reported as passed. Similarly, one successful concurrency test cannot be described as an absolute guarantee for every operating condition.
For important features, an independent reviewer should recheck the requirements and changes instead of relying only on the implementer’s summary. The reviewer should actively look for counterexamples such as abnormal process exits, duplicate callbacks, and transaction-commit failures.
8. Stage Handoffs: Preserve Decisions Instead of Accumulating Chat History
A useful handoff summary should be concise without becoming vague. Statements such as “most of the work is complete” are not sufficient.
A practical template is:
Current goal:Current stage:Confirmed facts:Adopted approach and rationale:Relevant files and key locations:Completed changes:Checks performed and results:Open questions and risks:Next smallest task:Areas that must not be changed:
At the start of a new session, ask the tool to restate the key constraints and next task before continuing. If important details are missing from the restatement, provide the missing information before requesting code changes.
Handoff documents also require maintenance. Outdated conclusions should be removed or marked invalid so that the handoff does not become another source of confusing context.
9. Match Process Weight to Task Risk
The four-stage workflow does not require extensive documentation for every change. Low-risk work, such as fixing wording or adjusting a local style, can use a short research and planning checklist. Features involving authorization, financial data, migrations, concurrency consistency, or cross-system interactions should retain complete evidence and review records.
The effectiveness of the process can be evaluated using practical indicators:
- Has rework caused by misunderstood requirements decreased?
- Are unplanned changes easier to detect?
- Does every acceptance item have corresponding evidence?
- Can the task still be restored accurately after a stage transition?
- When a defect appears, can it be traced quickly to an assumption, design decision, or implementation issue?
The key to AI-assisted programming is not making the tool generate as much code as possible in a single conversation. It is building a controlled information flow and decision flow:
- The research stage confirms facts;
- The planning stage constrains the solution;
- The implementation stage controls changes;
- The verification stage provides evidence.
Connecting these four stages turns complex feature development from an improvised activity into an engineering process that can be repeated, reviewed, and continuously improved.
