How to Design a Controllable and Auditable AI Coding Pipeline
This article explains how to turn AI coding from an open-ended conversation into an engineering process. It covers using a state machine to define the workflow, routing tasks by risk, separating the interaction, orchestration, execution, and enforcement layers, defining a primary artifact per stage, enforcing permission gates across files, commands, and context, binding verification results to a specific code baseline, handling exceptions and rollbacks, testing the pipeline itself, and starting from a minimal closed loop. Readers will learn the concrete rules and control mechanisms needed to make an AI agent a stable, auditable unit in a development workflow.
1. Start with the Goal: Turn AI Coding from a “Conversation” into an “Engineering Process”
An agent can understand requirements, modify code, and run checks. But stacking these capabilities together does not automatically produce a reliable development process. If every constraint lives inside a single prompt, three problems tend to appear in practice:
First, stage boundaries blur. Before a design is confirmed, the agent has already started editing code; after a review finds a problem, the fix is made directly inside the review stage, so review and implementation get mixed together.
Second, task state becomes unreliable. After a session is interrupted, the context is compacted, or the executor is switched, the system struggles to tell whether the current work is actually done and what should happen next.
Third, completion criteria stay vague. Natural-language conclusions like “already implemented” or “tests pass” are not enough as a delivery basis unless they are tied to a specific code version and execution evidence.
So the core of an AI coding pipeline is not a longer prompt, but an externally enforceable control mechanism:
- Use a state machine to decide how the flow advances;
- Use permission control to limit the scope of changes;
- Use structured artifacts to hand off between stages;
- Use verification evidence to decide whether delivery is allowed;
- Use event logs to support recovery and auditing.
The prompt guides reasoning and expression; the engineering mechanism constrains behavior and determines results. Only when the two work together do you get a stable, closed loop.
2. Define the Flow with a State Machine, Not by Asking the Model to Remember Steps
1. Model normal development and fault fixing separately
A regular requirement can follow this path:
Pending → Design → Plan → Coding → Simplification Review → Review → Verification → Done
A fault fix can follow a different path:
Pending → Fault Analysis → Coding → Simplification Review → Review → Verification → Done
The difference between the two paths is the goal of the starting work. Requirement design needs to make the expected behavior, interface boundaries, and impact scope explicit; fault analysis needs to establish reproduction conditions, locate the cause, and explain how the fix removes the problem.
Planning and simplification review can be optional stages, but skipping them must be decided by explicit rules, not by the agent’s ad hoc judgment.
2. The state record must be the single authoritative entry point
Which stage a task is in should be determined by a persisted state record, not inferred from chat content. At minimum, store the following fields:
| Field | Purpose |
|---|---|
| Task ID | Distinguishes different requirements and their artifacts |
| Current stage | Indicates the work being executed |
| State version | Prevents concurrent updates from overwriting each other |
| Execution round | Distinguishes the first run from rework |
| Next action | Identifies the stage executor to start |
| Artifact references | Links to the committed stage files |
| Code baseline | Identifies the code version the current checks target |
| Latest event | Records the reason for advancing, failing, or rolling back |
The key here is to separate “requesting an advance” from “actually advancing.” A stage executor may submit a completion request, but it should not directly change the task to done. Only after the orchestration layer checks the artifacts, permission records, and exit conditions can a legal transition be executed.
3. Transition conditions matter more than stage names
A flowchart with only arrows does not provide reliable control. Every transition needs an explicit condition, for example:
- Design to Plan: the design artifact is complete and key questions are resolved;
- Coding to Review: the change scope matches the authorization and the coding notes are submitted;
- Review to Verification: there are no unhandled blocking issues;
- Verification to Done: the required checks succeeded and the evidence matches the current code baseline.
The following is illustrative pseudocode only and does not correspond to any specific product interface:
function requestAdvance(task, expectedStateVersion, stageResult):check that the task state version matchescheck that the current stage allows this transitioncheck that the artifacts are completecheck for unauthorized operationscheck that the stage exit conditions are metif all checks pass:atomically write the new state and the transition eventotherwise:reject the advance and return the reason
Using a state version check and an atomic update prevents state overwrites when two executors work on the same task at the same time.
4. Not every loop is a problem
What you need to avoid is a free loop with no boundaries that cannot be audited, not every automatic scheduling loop. A mature orchestrator can keep pulling tasks continuously, as long as it has persisted checkpoints, timeouts, retry limits, and explicit exit conditions.
The principle: the loop handles scheduling, the state machine decides outcomes; executors cannot bypass the state machine to advance on their own.
3. Route Tasks by Risk, Not Just by Change Size
“Small requirements take a lightweight path, large requirements take the full path” is a reasonable starting point, but you cannot judge risk by file count or lines changed alone.
A change to a permission check may be tiny in code but can affect system security; a batch of formatting changes may touch many files but carry low business risk.
Recommended dimensions for grading tasks:
- Impact scope: does it cross modules, does it affect public interfaces.
- Behavior change: does it change business rules, exception handling, or compatibility.
- Data risk: does it involve schema changes, data migration, or irreversible writes.
- Runtime risk: does it involve concurrency, resource usage, and critical paths.
- Requirement certainty: are the acceptance conditions clear, are there many unknowns.
- Revertibility: can the change be undone quickly, does it need extra recovery steps.
Low-risk tasks can compress the design artifact, skip a separate plan or simplification review, but should still keep change boundaries, review, and verification. High-risk tasks should add human confirmation and a rollback plan.
A lightweight path means reducing unnecessary process cost, not abandoning necessary safety controls.
4. Separate the Interaction, Orchestration, Execution, and Enforcement Mechanisms
Clean layering lets you localize a problem to a specific responsibility boundary.
1. Interaction layer: receive user intent
The interaction layer submits requirements, shows progress, collects clarification, and receives approvals. It can offer a concise command entry point, but it should not directly decide whether a stage is complete.
When a user asks to “just make the change,” the system should still decide, based on risk rules, whether design or approval is needed.
2. Orchestration layer: decide the next step
The orchestration layer maintains the state machine, selects executors, validates transition conditions, handles failures, and controls retries. It cares about whether the flow is compliant, not about how the code is implemented.
3. Execution layer: complete a single stage
The execution layer is made up of stage executors with clear responsibilities. The design executor produces the approach, the coding executor produces the implementation, the review executor judges problems, and the verification executor runs checks and organizes evidence.
Stage executors should receive controlled input and submit results that follow the agreed contract.
4. Mechanism layer: enforce constraints that cannot be bypassed
The mechanism layer includes file access control, command authorization, runtime isolation, logging, and state update validation.
The role of this layer is to turn “don’t do this” into “you don’t have permission to do this.” For example, even if the review stage generates a fix suggestion, it cannot write directly to business code.
One thing to note in particular: pre-execution hooks are only effective when they cover every access entry point. If files can still be written or commands run through other channels, the gate is only a formality.
5. Define One Primary Artifact per Stage, but Do Not Read It as “Only One File Allowed”
Fixed artifacts help machines verify and lower handoff cost. Still, “one file per stage” is more accurately stated as: each stage has one fixed primary handoff artifact.
The coding stage will inevitably modify multiple source files; the verification stage may also generate logs and reports. The primary artifact should serve as an index of these changes and evidence, not a prohibition on necessary output.
A possible contract:
| Stage | Primary artifact | Allowed main write scope |
|---|---|---|
| Design | Design notes | The task’s design directory |
| Plan | Implementation plan | The task’s plan directory |
| Fault analysis | Analysis report | The task’s analysis directory |
| Coding | Coding notes | Authorized source files and the coding notes |
| Simplification review | Simplification suggestions | The simplification review directory |
| Review | Review report | The review directory |
| Verification | Verification report | The verification and evidence directories |
In this scheme, the coding stage is the only stage that writes to business source code. Simplification review only offers suggestions; if a suggestion needs to be implemented, the orchestration layer should send the task back to the coding stage, then re-review and re-verify.
This is easier to hold accountable than letting multiple stages modify code, and it avoids the confusion where “the review conclusion corresponds to the code before the change.”
Artifact content should be structured
Design notes should at least include the goal, non-goals, interface impact, risks, and acceptance conditions.
The implementation plan should break work into checkable steps, spell out dependencies, and state how each step is verified.
Coding notes should record the change scope, key implementation decisions, deviations from the plan, and open items.
The review report should separate blocking issues, general suggestions, and checks confirmed to be fine. Every issue needs a basis for its location, not just a vague “suggest optimization.”
The verification report must state the check target, execution environment, what was checked, the results, and where the evidence is stored.
The value of an artifact is not its word count, but whether the next stage can act on it accurately.
6. Permission Gates Must Cover Files, Commands, and Context
1. File permissions: limit paths and protect the control plane
An executor can only write to paths allowed for the current task and current stage. The state record, permission configuration, and historical evidence belong to the control plane and should be managed by trusted components.
Path validation should also handle normalized paths, symbolic links, and out-of-bounds references, so that a path that appears allowed does not ultimately point to a protected location.
Parallel tasks should use separate directories to prevent fixed artifact names from overwriting each other. Artifacts from historical rounds should not be rewritten directly; keep versions or create a new round record.
2. Command permissions: do not check only the command name
Whether a command is safe depends on the executable, the arguments, the working directory, environment variables, and the scope of resource access. Even if a certain type of check command is usually safe, arguments can trigger writes, network access, or other side effects.
A more robust approach:
- Deny unauthorized operations by default;
- Explicitly authorize necessary operations;
- Run checks in an isolated environment;
- Set timeouts and resource limits;
- Require extra confirmation for high-risk operations;
- Record execution arguments, exit status, and output evidence.
Do not inherently trust build and test processes either, because they may run scripts in the repository. The isolated environment should avoid carrying production credentials and unrelated sensitive information.
3. Context permissions: provide only the information needed for the current stage
The design stage needs requirements and architecture information; the review stage needs design constraints, code diffs, and related context; the verification stage needs acceptance requirements, how to run, and the target code baseline.
Do not open the full historical session to every stage by default. Excess context adds noise and can also make an old conclusion be treated as a current fact.
Repository docs, comments, and external text should be treated as data to be analyzed, not as control instructions that can change pipeline permissions. Permission rules must come from a trusted control plane.
7. Bind Verification Results to a Specific Code Baseline
“Verification passed” is only meaningful when the check target is clear.
A valid piece of verification evidence should at least answer:
- Which code version or file digest was checked;
- What environment and configuration were used;
- Which checks were run;
- Which succeeded, which failed, and which were not run;
- Where the raw output is stored;
- Which execution round produced the conclusion.
Once the code or a key configuration changes, an old verification result cannot automatically carry over as passing evidence for the new version.
Verification should select a combination based on risk, including static checks, build, unit tests, integration tests, and scenario acceptance. For a fault fix, also confirm that the original problem can be reproduced and that the corresponding regression check passes after the fix.
You must distinguish “check passed,” “check not run,” and “check result uncertain.” When the run conditions are missing, you can report a blockage and request human handling, but you cannot write “no failures found” as “all passed.”
8. Make Exception Rollback Part of the Flow
Real development rarely runs the main path to completion in one pass. A reliable pipeline should define the following exceptions in advance:
- Unclear requirement: enter a waiting-for-clarification state and do not keep guessing the implementation.
- Execution timeout or interruption: keep a checkpoint, retry by rule or hand off to a human.
- Review failed: return to the coding stage with a structured issue list.
- Verification failed: first decide whether it is an implementation problem, an environment problem, or a problem with the check itself, then choose the rollback target.
- Design flaw found: return to the design stage rather than forcing a patch-style fix in the coding stage.
- Permission violation: reject the operation and log the event, pausing the task if necessary.
Every rework round should have its own number and be linked to the issue source, the changes made, and the new verification evidence. Retries must have a limit; past the threshold, hand off to human judgment to avoid consuming resources continuously with no real progress.
When recovering a task, read the authoritative state and confirmed artifacts, rather than asking the model to continue from memory.
9. Test the Pipeline Mechanism First, Then Evaluate Coding Quality
An agent that can generate correct code does not mean its flow control is reliable. The pipeline itself needs testing.
At minimum, cover:
- Can a normal task complete along a legal path;
- Are optional stages skipped by rule;
- Can advancement be blocked when an artifact is missing;
- Can non-coding stages be prevented from modifying source code;
- Can completion be rejected when verification evidence does not match the code baseline;
- Can the task recover after a session interruption;
- Can concurrent updates avoid state overwrites;
- Does a repeated completion request stay idempotent;
- After a review failure, does it enter the correct rework path;
- Can a high-risk task trigger human approval.
After running, watch the first-pass verification rate, rework rounds, number of blocked unauthorized attempts, stage durations, reasons for human intervention, and recovery success. These metrics are for finding process bottlenecks, not for simply pursuing fewer reviews or faster completion.
10. Start from a Minimal Closed Loop
Early on, there is no need to build many stages and complex scheduling at once. You can start with a minimal closed loop of “Design—Coding—Review—Verification”:
Step 1: define the states, allowed transitions, and the exit conditions for each stage.
Step 2: create primary artifact templates for each stage to keep handoff information stable.
Step 3: tighten source write permissions so the coding stage becomes the only implementation entry point.
Step 4: bind verification evidence to the code baseline and forbid completion without evidence.
Step 5: add failure rollback, interruption recovery, and human approval.
Step 6: then, based on the actual task distribution, add lightweight paths, a separate plan, and simplification review.
The maturity of an AI coding pipeline does not depend on how many nodes the flowchart has, but on whether four questions can be answered clearly: what state are we in now, what permissions does the current executor have, what evidence is needed to complete this stage, and where should we return after a failure.
Turning these answers into enforceable rules is what lets an agent go from a helper that relies on ad hoc judgment to a stable execution unit in a controllable development process.
