跪拜 Guibai
← Back to the summary

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

  1. 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.
  2. 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.
  3. 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?

2. What is an Independent Agent (e.g., Independent Reviewer Agent)?

3. What is a SubAgent?


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:

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?'

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'

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

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?'

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

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

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:

  1. 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.
  2. 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.
  3. 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.
  4. Coder completes implementation: Modifies the confirmed connection and state-update path, submits the diff and static-check results, and passes the implementation checkpoint.
  5. 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.
  6. 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.
  7. 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.

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:

  1. 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.
  2. 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.
  3. 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:

  1. A skill for initializing a new page (base-new-page): tells the AI what work a new page should include.
  2. A skill for converting UI to code (figma-to-compose): tells the AI how to convert Figma designs to Compose code.
  3. 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.
  4. A skill for writing popups: center popups, bottom popups, global popups, etc. Any project-standard pattern can become a skill.
  5. 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.

  1. Via phased roles and a blocking state machine, control every decision point from requirements to code, using determinism against model randomness.
  2. Via a Main Agent running throughout plus an independent Agent for review, maintain overall coherence and reduce omissions from self-confirmation bias.
  3. 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.
  4. 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.

Note: This article was generated by AI based on project practice plus my thoughts and experience; I reviewed and revised it. Please critique any errors.

Comments

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."

TimeFine

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.

TimeFine

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.