A Blueprint for AI Coding Workflows: Phases, Checkpoints, and Independent Reviewers
highlight: androidstudio theme: juejin
In day-to-day development, feeding a large language model a direct "help me implement this feature" or "fix this bug" often falls into the loop: generate code → deviation from original requirements/technical design or compile errors → fix deviations/errors → finish this round. How can you guarantee quality in a single-turn conversation? The root causes are: missing necessary context constraints, unclear decision boundaries, and the confirmation bias that models struggle to overcome when self-reviewing.
This article shares some lessons in designing AI development workflows (dev-workflow and bugfix-workflow). It focuses on decision-chain construction, state-machine constraints, and Agent role division, and why complex projects need a coordinated Main Agent, independent Agents, and subAgents.
1. Why Do You Need a Structured Workflow?
In complex projects, writing code is only the end of the whole development chain. Coding directly without clarifying the requirement background and boundaries easily leads to design deviation. Therefore, our workflow is divided into clear phases, each with a specific role and responsibility:
flowchart TD
Phase0[Phase 0: Background Analysis] --> Phase1[Phase 1: Architecture and Solution]
Phase1 --> Phase2[Phase 2: Code Implementation]
Phase2 --> Phase3[Phase 3: Independent Review]
Phase3 --> Phase4[Phase 4: Evidence Verification]
Phase4 --> Phase5[Phase 5: Delivery and Archival]
Phase and Role Definitions
| Phase | Role | Core Responsibility | Why It Can't Be Skipped |
|---|---|---|---|
| Phase 0 | Context Analyst | Organize existing requirements, related code relationships, and external dependencies (e.g., hardware protocols, interface specs) | Avoid forgetting existing requirement details; prevent model hallucination or ignoring existing context constraints |
| Phase 1 | Planner | Design state flow, define module boundaries, create technical solutions and acceptance criteria | Freeze architecture decisions before touching code, ensure implementation path is transparent |
| Phase 2 | Coder | Write or refactor code according to the confirmed solution | Strictly modify within the scoped engineering range; no improvisation beyond the solution |
| Phase 3 | Reviewer | Independently inspect code diffs, check race conditions, memory leaks, and boundary exceptions | Break the 'self-write, self-review' mindset and provide an objective review perspective |
| Phase 4 | Tester | Run static checks, corroborate existing evidence, and list required manual verification items against acceptance criteria | Confirm delivery based on objective evidence rather than assumptions like 'looks fine' |
| Phase 5 | Delivery Coordinator | Aggregate changes, review conclusions, verification scope, and follow-up items; update documentation as needed | Avoid scattered partial conclusions; ensure delivery state is traceable |
2. State Machine: Use Determinism Against Model Randomness
Large models are prone to context drift in long sessions, e.g., generating code before confirming requirement details, or blindly skipping fixes after a review failure.
To address this, we introduce a state machine with checkpoint mechanisms into the workflow:
stateDiagram-v2
[*] --> ContextAnalysis
ContextAnalysis --> BackgroundPending: Background organization complete
BackgroundPending --> Planning: Background approval passed
BackgroundPending --> ContextAnalysis: Supplement background
Planning --> ProposalPending: Solution and acceptance criteria complete
ProposalPending --> Coding: Approval passed
ProposalPending --> Planning: Revise solution
Coding --> ImplementationPending: Implementation and static checks complete
ImplementationPending --> Reviewing: Implementation verified and released
ImplementationPending --> Coding: Implementation feedback
Reviewing --> ReviewFixing: Review failed (with evidence list)
ReviewFixing --> Reviewing: Re-review after targeted fix
Reviewing --> Testing: Independent review passed
Testing --> VerificationFixing: Verification found issues
VerificationFixing --> Testing: Re-verify after targeted fix
Testing --> Delivery: Checks passed, pending manual items disclosed
Delivery --> [*]: Summarize delivery and archive
Three Hard Rules for the Checkpoint Mechanism
- Key decisions are separately gated: Background, solution, and implementation correspond to Checkpoint #0, #1, and #2. Confirmation of background precedes planning, confirmation of solution precedes coding, and implementation results must be verified and released before entering independent review. Each release only advances the current checkpoint to the next legal stage.
- Failure count limit for review and verification: Phase 3 and Phase 4 each record consecutive failure counts. After 3 failures, work is forcibly paused for human engineer intervention. Re-fixing does not reset the counter, preventing infinite self-repair loops.
- Evidence-driven reliable delivery: Before entering the delivery phase, actual static checks, usable logs, screenshots, or other verification evidence must be provided, with acceptance status marked line by line. Items still requiring compilation, runtime, or physical-device confirmation must be explicitly listed. Subjective descriptions or static results cannot replace runtime conclusions.
3. Understanding Multi-Agent Architecture: Main Agent, Independent Agent, and SubAgent
As AI workflows evolve, the limitation of a single Agent becomes obvious: when tasks grow large and context becomes long, a model in a single context faces attention scattering, logic confusion, and severe confirmation bias. Therefore, a multi-Agent architecture is necessary.
In practice, we must clearly distinguish their responsibilities and value:
1. What is the Main Agent?
- Role: The project manager and core brain of the entire task.
- Responsibilities:
- Control overall progress, maintain core context (original requirements, architecture solution, main deliverables).
- Drive the state machine from Phase 0 to Phase 5.
- Coordinate globally, dispatch subtasks as needed, and aggregate, verify, and arbitrate results from subAgents.
- Why indispensable: Without a Main Agent, tasks fragment into a leaderless mess; it is the only anchor keeping the entire development pipeline logically coherent.
2. What is an Independent Agent (e.g., Independent Reviewer Agent)?
- Role: An external expert with its own task context.
- Why needed (break confirmation bias):
- In the traditional single-Agent mode, the same Agent writes and reviews code. When it 'reviews itself', the historical context is full of 'this is what I was thinking', 'this logic seems fine', and the model subconsciously defends its own code, missing subtle bugs like race conditions or boundary exceptions.
- The independent Agent has a separate context boundary. It reads the latest background, the requirements contract, the architecture solution, the actual code diff, and necessary code context. It does not inherit the full coding conversation or the implementer's self-assessment. It needs business context but is not led by the implementer's reasoning, thereby reducing confirmation bias.
3. What is a SubAgent?
- Role: Dynamically spawned by the Main Agent to handle specific heavy subtasks (e.g., an evidence-investigation subAgent).
- Why needed (decoupling and noise management):
- Context pollution control: When debugging complex bugs (e.g., Bluetooth communication failures, data sync anomalies), there are often megabytes of runtime logs or multiple screenshots. Feeding all of this to the Main Agent quickly exhausts the main session's context window and introduces noise.
- Parallel investigation and cost reduction: A subAgent can deeply mine large logs, time-series data, or interface contracts in its own context. After filtering irrelevant information, it returns structured fact summaries and key evidence to the Main Agent. Independent investigations run in parallel as needed, protecting the Main Agent's attention and improving debugging efficiency. Actual benefits still depend on task scale and handoff cost.
4. Making Agents Truly Enter the Workflow: From Role Division to Delivery Closure
After clarifying roles, we must put them back into real development tasks and establish a clear collaboration chain: who drives progress, what is handed off, when to move to the next phase, and what happens after failure.
The key is that each phase solves a different problem and delivers a checkable result to the next phase. Role division only becomes an executable workflow when bound to inputs, outputs, permissions, and failure handling.
1. First, Separate Two Dimensions: Work Responsibilities and Collaboration Style
Roles mentioned earlier fall into two different dimensions:
- Context Analyst, Planner, Coder, Reviewer, Tester: describe 'what responsibility is taken on now'. They focus on background, solution, implementation, review, and verification respectively.
- Main Agent, Independent Agent, SubAgent: describe 'who organizes the task, how context is divided, how work is delegated'.
Thus, five work responsibilities do not mean starting five Agents each time. In this design, the Main Agent defaults to the Context Analyst, Planner, Coder, Tester, and the final Delivery Coordinator; the independent Reviewer Agent uses a separate task context in Phase 3; the evidence-investigation SubAgent is engaged on demand when log analysis or time-series reconstruction is complex.
A single SubAgent can also take on the independent Reviewer role, provided it uses an independent review context and did not participate in forming the implementation or diagnostic conclusion. Here, 'independent' emphasizes review perspective and context boundary; 'SubAgent' emphasizes task delegation. They are not mutually exclusive product types.
Human engineers retain decision rights over business goals, solution trade-offs, and phase gating. The Main Agent can organize and push forward, but cannot replace humans in confirming requirements, nor can it let the independent Reviewer Agent declare a review passed.
2. How Do Phases Hand Off?
Phase 0: Context Analyst First Confirms 'What Problem Are We Solving?'
- Input: User description, existing requirements, related code, historical decisions, and any available interfaces, device protocols, or failure materials.
- Work content: Restore the functional goal, distinguish current behavior from target behavior, list impact scope, rules that must be preserved, and key unknowns.
- Deliverable: Background analysis and description of the original requirement. For bug fixes, form a failure baseline with 'trigger condition, expected result, actual behavior, evidence source'.
- Handoff condition: After the human engineer confirms the background and problem boundary, move to planning. Background confirmation only means both sides understand consistently; it does not mean the root cause is located.
For example, when a user reports 'Bluetooth reconnect fails', the Context Analyst must first determine: how connections were established in the requirements, why it isn't established now, whether the page doesn't update after successful connection, or whether the old connection still triggers callbacks after switching devices. These situations look similar but require completely different fixes.
Why this phase is needed: Models easily treat the phenomenon in the user's description as the cause. Without a failure baseline, even if the code is written correctly later, it may fix a different problem.
Phase 1: Planner Turns Background Into a 'Implementable, Reviewable, Verifiable Solution'
- Input: Confirmed background and boundaries, related code relationships, and necessary investigation evidence.
- Work content: Define the scope of changes and non-changes, design state flow, module responsibilities, exception handling, and compatibility strategies; list implementation tasks and acceptance criteria.
- Deliverable: Technical solution and verification contract. The contract states how each acceptance criterion will be checked, what evidence is needed, and which items depend on manual or physical-device verification.
- Handoff condition: After human confirmation of the solution, the Coder can start modifying code.
In bugfix-workflow, the Main Agent also takes on the Investigator role first, cross-checking code against failure evidence, then designs the fix as Planner. When evidence is insufficient, it should clearly state whether to continue evidence gathering or implement the fix; a guess must not be packaged as a confirmed root cause.
Why this phase is needed: The solution makes 'how the model plans to change' visible before coding; acceptance criteria define 'what counts as done' in advance, preventing the model from picking favorable completion conditions after writing code.
Phase 2: Coder Implements Within Confirmed Boundaries
- Input: Confirmed solution, permitted module/file scope, project conventions, and acceptance criteria.
- Work content: Read related code, implement against the task list, reuse existing capabilities, and run lightweight static checks within the permitted scope.
- Deliverable: Actual code diff, changed file list, static check results, and deviation notes from the original solution.
- Handoff condition: The Main Agent aggregates implementation results; after human verification and release of the current checkpoint, hand off to the independent Reviewer.
If during coding the Coder finds that an interface the solution depends on doesn't exist, or the existing lifecycle can't support the design, it must feed facts and impact back to the Main Agent to update the solution and acceptance criteria. For substantive trade-offs, the human engineer confirms; the Coder must not silently expand scope or change the goal.
Why the permission constraint is needed: Models often refactor surrounding code while implementing one feature. Restricting the Coder's modification scope controls the diff size and lets follow-up reviews more easily identify changes that actually affect behavior.
Phase 3: Independent Reviewer Checks 'Is the Goal Achieved and Is the Engineering Reliable?'
- Input: Latest background, confirmed solution, acceptance criteria, actual code diff, necessary calling context, and project conventions.
- Work content: Conduct both requirements correctness and engineering correctness review. The former checks whether the wrong goal was implemented, rules were missed, or scope was exceeded; the latter checks coroutines and lifecycles, async race conditions, exception handling, resource release, and other engineering issues.
- Deliverable: Review conclusion and issue list. Issues include code location, trigger condition, specific impact, and basis for the judgment.
- Handoff condition: After review passes, proceed to verification; if failed, the Main Agent verifies the issues, organizes the Coder for targeted fixes, and sends back to the independent Reviewer for re-review.
The Reviewer does not directly take over business implementation. This preserves the responsibility chain of 'raise issue - fix issue - re-review result', preventing a reviewer from modify code and then approving its own changes.
Why independent context must be preserved: The Main Agent switching to 'now I am Reviewer' does not clear its previous implementation thinking. The independent Reviewer must re-judge based on requirements, solution, and code, not continue the Coder's self-explanation.
Note: If the development or fix is trivial, a separate Reviewer Agent is unnecessary; review can be done directly in the Main Agent.
Phase 4: Tester Checks 'Which Results Are Backed by Evidence' Against Acceptance Criteria
- Input: Latest implementation after review, verification contract, failure baseline, and available logs, screenshots, or other verification materials.
- Work content: Check each acceptance criterion line by line, verify the original trigger scenario, adjacent normal paths, and related boundaries; distinguish passed, failed, and pending-human-verification items.
- Deliverable: Verification report listing actual checks executed, evidence sources, unexecuted items and reasons, and a human regression checklist when needed.
- Handoff condition: Known failures enter targeted rework; items with sufficient evidence can be marked passed; items not yet run remain pending verification.
Under Android engineering constraints, the AI by default executes static checks, logic verification, and existing-evidence analysis; it does not proactively compile the project or add test cases. Compilation, runtime, and physical-device verification follow the manual verification list or subsequent explicit authorization. Therefore, the Tester must clearly distinguish 'static check passed' from 'physical-device behavior verified' and cannot replace the latter with the former.
Why verification is needed after review: The Reviewer judges whether the code has identifiable issues; the Tester checks whether acceptance goals have supporting evidence. Especially in device-communication scenarios, callback order, hardware state, and network environment can make code reading diverge from actual behavior.
Phase 5: Delivery Coordinator Aggregates Delivery and Preserves Continuable Context
- Input: Final implementation, review report, verification report, and necessary background/requirement records.
- Work content: Summarize change scope, key decisions, verification conclusions, unresolved issues, and follow-up items; update relevant documentation as needed.
- Deliverable: Delivery description traceable to files and evidence, plus a clear list of pending manual verification items.
- Completion boundary: If physical-device or hardware items remain unverified, explicitly mark 'implementation and static verification completed, runtime behavior pending verification' and do not blanket-claim all passed.
Why a unified wrap-up is needed: The local conclusions of multiple Agents only answer the user's real questions when aggregated by the Main Agent: what changed, what was solved, why it was judged that way, and what remains unconfirmed.
3. How Does a SubAgent Participate, and Why Doesn't It Own the Whole Flow?
The evidence-investigation SubAgent typically engages in Phase 0 or Phase 1; in Phase 4 it can be reused for complex before/after comparisons. Its task should be concrete, for example:
Analyze the logs of this device during this round of reconnection, sort out disconnections, retries, connection callbacks, and page state updates in chronological order; separate observed facts from unconfirmed causes; provide key log locations.
The SubAgent returns a timeline, key evidence, the scope of conclusions, and open questions. The Main Agent then cross-checks these facts with business context and code relationships to form a diagnosis or solution.
This boundary is crucial: the investigation Agent provides evidence, the Main Agent organizes decisions, and the independent Reviewer reviews implementation. An investigation Agent that participated in the diagnosis does not double as the independent Reviewer for the same task, preventing it from maintaining its earlier judgments during review.
Also, having independent context does not naturally mean the working directory or device is isolated. When multiple Agents share a project or device, file ownership and operation order must still be explicit; page operations, pairing, or evidence collection on the same device should be handled by one executor to avoid interference.
4. Walking Through a Bluetooth Reconnection Fault
Suppose a user reports: after switching devices, the page occasionally shows 'connected', but the current device is actually not connected. Here is a hypothetical handling process:
- Context Analyst confirms the goal: After switching devices, the page only reflects the current target device's connection state; normal reconnect capability must be preserved. Background and boundaries are confirmed by the human engineer.
- Investigation SubAgent organizes evidence: The timeline shows that the old device's success callback arrives after the device switch, and subsequently the page state updates. This ordering still needs to be cross-checked with the code call chain; the root cause cannot be declared from logs alone.
- Planner creates a solution: After cross-checking, it confirms the old session callback can write to the current state, so the plan includes session identifier verification, old-task cancellation, and state ownership constraints. Acceptance criteria cover ignoring old callbacks, successful current connections, and correct failure-state display.
- Coder completes implementation: Modifies the confirmed connection and state-update path, submits the diff and static-check results, and passes the implementation checkpoint.
- Independent Reviewer raises questions: The success callback adds session verification, but will the failure callback also pollute the new session? After page exit, can a timeout task still update state? Confirmed issues go back to the Coder for rework and then re-review.
- Tester checks results: Compares the same trigger conditions and checks evidence from the fixed version; old-version logs serve only as the failure baseline. Items without physical-device results are explicitly left on the manual verification list.
- Delivery Coordinator aggregates delivery: Describes the fix path, review conclusions, verified scope, and remaining items, so subsequent verification can continue along the same acceptance criteria.
Throughout this process, the workflow answers seven questions in sequence: what is the goal, what is the phenomenon, what is the evidence for the cause, how will it be fixed, are there gaps in implementation, do results have evidence, and what remains unknown. Any missing step can be traced to a specific responsibility and deliverable, rather than making the model guess from scratch.
5. Why Do dev-workflow and bugfix-workflow Share a Skeleton but Have Different Entry Points?
| Comparison Dimension | dev-workflow |
bugfix-workflow |
|---|---|---|
| Core goal | Implement confirmed new behavior, or refactor while preserving external behavior | Restore behavior that should have been true |
| Background focus | User scenarios, requirement value, functional boundaries, existing capabilities | Original requirements, current effective rules, abnormal deviations, failure baseline |
| Solution basis | Requirement constraints, existing architecture, technical trade-offs | Cross-checking code with failure evidence, cause judgment, minimal fix scope |
| Acceptance focus | Whether the new goal is achieved, whether existing capabilities are affected | Whether the original fault is eliminated, whether adjacent normal paths are preserved |
Both flows share phases, approvals, and independent review to reduce duplicate rules; separately defining background and solution focus prevents the model from expanding 'fix a problem' into 'redesign a feature', or mistaking a genuinely new requirement for a local patch.
6. The Necessity of This Workflow: Stop Errors Earlier and More Clearly
A structured workflow adds costs for background organization, solution explanation, and independent handoffs, but it reduces the cost of repeatedly implementing, debugging, and rolling back when wrong decisions enter code.
- Background phase intercepts goal errors: Avoids treating designed behavior as a bug, or mistaking user phenomena for root causes.
- Solution phase intercepts decision errors: Exposes issues in state flow, module boundaries, and acceptance conditions before code generation.
- Implementation phase intercepts scope runaway: Every modification maps to a confirmed task, reducing unrelated refactors and additional risk.
- Independent review intercepts implementation gaps: Introduces a perspective not involved in coding, checking requirement deviations and engineering defects.
- Evidence verification intercepts false completion: Separately records 'looks reasonable', 'static check passed', and 'runtime behavior verified'.
- Main Agent wrap-up intercepts handoff loss: Preserves conclusions, reasoning, and open items so the next round can continue.
These mechanisms cannot guarantee the model never errs, but they make errors surface earlier, keep impact controllable, and make completion conclusions easier to verify. For device communication, async state, and cross-module changes, this traceability is the main value; for simple tasks, reports and investigation scope can be compressed to avoid ineffective collaboration just for the sake of role completeness.
5. Context Isolation and Token Control Strategies
When introducing multi-Agent and subAgent architectures, watch for token explosion and handoff runaway. Reasonable architecture design can trade controlled collaboration cost for higher determinism:
- Precise handoff, no full copy: When delegating to a subAgent or independent Agent, the Main Agent passes the goal, necessary background, constraints, relevant code and diff, and structured contract, avoiding transmitting tens of thousands of lines of historical chat. Necessary background must be sufficient to understand the task; trimming context cannot come at the cost of missing requirement boundaries.
- Return only fact summaries, not raw exploration processes: After a subAgent parses large logs or performs multiple code lookups, it returns only structured conclusions and key evidence (e.g., file line numbers, key log lines) to the Main Agent, labeling facts, inferences, and unknowns. Raw exploration material stays in the sub-context or investigation records for on-demand retrieval.
- Enable on demand, avoid over-design:
- Lightweight tasks that a single Agent can handle: mechanical single-file modifications, local UI copy adjustments, or short log interpretation do not need the full development process; the Main Agent can do them directly. Don't split tasks just to have all roles present.
- Enable multi-Agent collaboration: when entering the two structured workflows described here, Phase 3 keeps the independent Reviewer; an additional investigation SubAgent is engaged on demand, e.g., to correlate logs across multiple runs, reconstruct complex sequences, or investigate across independent domains (like API contracts and low-level communication protocols). Whether to delegate depends on workload and task independence, not a mechanical log-line count.
6. Workflows Need Skills
A workflow is an encapsulated coding process, but how do you produce high-quality code that fits the project's encapsulation? This requires combining detailed, practical low-level skills distilled from the project. This foundational work must be solid.
Skill encapsulation is essentially distilling programmers. For example, how popups are written in a project, a programmer knows; that knowledge should be encapsulated into a skill so the AI knows it too. Although the AI could read code, reading source is time-consuming and the AI may hallucinate and deviate. A programmer may have encapsulated the pattern, but the AI might adopt a lower-level implementation, going off track.
Common Android skills include:
- A skill for initializing a new page (
base-new-page): tells the AI what work a new page should include. - A skill for converting UI to code (
figma-to-compose): tells the AI how to convert Figma designs to Compose code. - A skill for converting interfaces to network requests (
api-to-request): tells the AI how to write a network request from an interface. Request types include single, serial, concurrent, each with different patterns; multiple skills can exist. - A skill for writing popups: center popups, bottom popups, global popups, etc. Any project-standard pattern can become a skill.
- Others: pull-to-refresh/load-more skills, Adapter writing skills, code quality inspection skills, page-lag skills, and so on.
7. Summary
The core of a structured workflow is trusting AI based on systems and constraints, not on occasional model performance.
- Via phased roles and a blocking state machine, control every decision point from requirements to code, using determinism against model randomness.
- Via a Main Agent running throughout plus an independent Agent for review, maintain overall coherence and reduce omissions from self-confirmation bias.
- Via explicit inputs, deliverables, and rework paths, close the loop on each Agent's responsibilities, ensuring 'background - solution - implementation - verification' always targets the same goal.
- Via an evidence-investigation subAgent isolating noise and a verification report disclosing unknowns, protect the main context's cleanliness and efficiency, giving complex engineering AI-assisted development a traceable and verifiable delivery foundation.
Top 1 of 3 from juejin.cn, machine-translated. The original thread is authoritative.
I agree with splitting into phases, especially that Coder and Reviewer shouldn't be the same self-review. What easily fails is: if the review side can still see the reasoning behind the implementation and the same conversation, confirmation bias just moves to a new location. Now I give the reviewer only three things: frozen acceptance criteria, the diff, and the failing checks, not the "why I wrote it this way." Also, for human approval gates like background approval, when people get tired they just click approve. What can stop drift is machine-decidable invariants, like compilation, contract tests, or failing immediately if files outside the scope are touched — not calling another model to say "pass."
1. The independent Reviewer Agent gets the proposal, acceptance criteria, and diff; it collects necessary context itself, like requirements and current implementation. It operates independently of the main agent, as a review role, not depending on the main agent's environment context, making the reviewer more accurate. This is written in section 4.2, Phase 3. 2. Currently my design has 3 places where "pass" is needed, but I think all of them require human engineer involvement. The first is background analysis: because with AI writing lots of code, human engineers can no longer remember the original requirements, and might give completely wrong directions, so the background of the change needs to be explained. The second is proposing a solution: the proposal gives how to change, which files will be affected, file risk levels, and the technical approach, to avoid AI mis-modifying or wrong technical approach or wrong files. The third is confirming the code implementation: at this step AI has finished writing the code, but many models have their own flaws, like GPT's over-defensive programming; here the human engineer can step in and modify, or if they don't want to review or change, they can pre-enter a confirmation. All 3 of these came from lessons learned. The later phases are all auto-executed by AI.
This workflow also has some auxiliary things, for example: 1. Background analysis reads the AI-generated requirements document combined with the code implementation; 2. The technical solution and code are combined with project-encapsulated detailed skills, such as page UI, dialogs, network requests, basic page construction, code quality checks, etc. The foundational work must be solid, constraining code quality within a controllable range according to the project architecture.