Dual-Engine AI Coding: A Layered Approach to Planning and Execution
While AI coding assistants excel at simple tasks, they struggle with complex, cross-module development. This article explores a layered collaborative architecture that separates planning and reasoning from execution operations, detailing its responsibilities, interaction protocols, and engineering implementation strategies to improve task completion and maintain safety.
Dual-Engine AI Coding: A Layered Approach to Planning and Execution
1. The Problem: Why Single Models Struggle with Complex Development Tasks
Current AI coding assistants demonstrate high usability in scenarios like code completion and single-function generation. However, when tasks scale up from “writing a function” to “fixing a cross-module bug,” “completing a dependency upgrade while ensuring tests pass,” or “implementing a full feature based on a requirements document,” the limitations of end-to-end execution by a single model become apparent: the context window is insufficient to hold all relevant code, long-chain reasoning tends to lose the goal midway, side effects of tool calls are difficult to undo, and errors accumulate and amplify over multiple steps.
The industry has gradually reached a consensus in practice: separate “figuring out what to do” from “actually doing it,” assigning distinct responsibilities to different capability layers, and coordinating them through explicit protocols. This aligns closely with human engineering team collaboration—architects design solutions and decompose tasks, while engineers handle specific implementation and verification. This article discusses the responsibility boundaries, interaction protocols, and engineering implementation key points of the planning reasoning layer and the execution operation layer in intelligent coding systems based on this layered collaborative approach.
2. Layered Architecture: Division of Responsibilities
2.1 Planning and Reasoning Layer: Understanding, Decomposition, and Decision-Making
The core responsibility of the planning reasoning layer is not to directly produce final code, but to transform vague user intent into structured, executable, and verifiable task plans. Specifically, this includes:
- Intent Clarification and Context Construction: Extract key constraints from requirement descriptions, code repositories, and conversation history. Identify ambiguities and proactively request clarification rather than blindly executing with insufficient information.
- Task Decomposition and Dependency Sorting: Break down large tasks into moderately sized subtasks, clarifying sequential dependencies and parallelizable relationships to form a Directed Acyclic Graph (DAG) of tasks.
- Solution Trade-offs and Risk Prediction: Compare multiple implementation paths regarding cost, impact scope, and rollback capability. Select a relatively robust approach and flag high-risk steps.
- Acceptance Criteria Definition: Predefine the “done” conditions for each subtask, such as successful compilation, specific test cases passing, or no new static analysis warnings, preventing the execution layer from operating in a silo.
The output of the planning reasoning layer should be a machine-readable task plan, not a natural language suggestion. Each step in the plan must include the objective, inputs, expected outputs, acceptance criteria, and failure handling strategy. This level of structuring directly determines the controllability of subsequent execution.
2.2 Execution Operation Layer: Tool Invocation and Result Feedback
The execution operation layer does not bear the responsibility of “thinking.” It receives specific steps from the planning layer, invokes appropriate tools to complete the operations, and returns structured results. Typical capabilities include:
- File System Operations: Read, write, modify, and rename files, with traceable diff records generated for every write.
- Command Execution: Run build, test, static analysis, and formatting commands, capturing standard output, standard error, and exit codes.
- Version Control Operations: Create branches, stage changes, and generate commits, ensuring every step of the change is rollbackable.
- Retrieval and Querying: Perform symbol search and content queries within codebases, documents, and logs to provide factual basis for the planning layer.
The key design principle for the execution layer is idempotency and rollbackability. Any operation with side effects should have a corresponding undo path, such as backing up the original file before writing, recording the workspace state before command execution, and organizing changes at independent commit granularities. This way, even if the planning layer makes a misjudgment, the system can safely roll back to a known good state.
2.3 Collaboration Protocol Between the Two Layers
The interaction between the two layers should follow a closed loop of “Plan - Execute - Observe - Replan”:
plan = planner.decompose(task, context)for step in plan.steps:precondition_check(step)result = executor.run(step)observation = normalize(result)if not step.acceptance(observation):plan = planner.revise(plan, step, observation)continue_or_abort(plan)
It is important to emphasize that the planning layer should receive normalized observation results after each execution round, rather than a flood of raw logs. The execution layer is responsible for cropping and summarizing command output into key information digestible by the planning layer, preventing the context from being filled with noise. Additionally, the planning layer retains the ability to abort the task and request human intervention at any time—this is the safety baseline.
3. Key Design Points for Engineering Implementation
3.1 Context Management: Tiered Supply Instead of One-Time Infusion
The planning layer and execution layer have different context requirements. The planning layer needs high-level abstract information: task objectives, module boundaries, interface contracts, and historical decision records. The execution layer needs precise local information: the current content of the target file, relevant symbol definitions, command working directory, and environment variables. Providing all context to both layers simultaneously wastes window space and introduces interference.
The recommended approach is to establish a tiered context supply mechanism: the planning layer maintains a “task status summary” that updates dynamically as execution progresses; the execution layer only receives the exact segments needed for the current step. The summary is driven by execution results rather than raw log accumulation, maintaining information timeliness and relevance within a limited window.
3.2 Permission Isolation and Security Boundaries
The execution layer directly interacts with the file system and command channels, requiring explicit permission boundaries:
- Write operations are restricted to the task’s declared working directory; out-of-bounds writes are rejected directly.
- Command execution uses a whitelist mechanism, allowing only predefined safe command categories and prohibiting arbitrary script concatenation.
- Sensitive operations (such as deleting files, modifying configurations, or pushing to remote) require explicit tagging by the planning layer and trigger a secondary confirmation.
- All operations record audit logs, including time, operation type, target, and result summary, for post-mortem traceability.
3.3 Failure Handling and Retry Strategies
A major advantage of the layered architecture is that failures can be localized. When a step fails in the execution layer, the planning layer receives structured failure reasons (exit code, error type, key stack trace) to decide whether to retry, change paths, or abort. An anti-pattern to avoid is the execution layer “guessing intent” on its own and bypassing the failure to continue executing—this causes the state to deviate from the plan and makes convergence difficult.
Retry strategies should distinguish between transient failures (such as network jitter or temporary resource contention) and logical failures (such as test assertion failures or type mismatches). The former can be retried with limited backoff, while the latter must return to the planning layer for a new decision. Each retry should record the attempt count and differences to prevent infinite loops.
3.4 Observability: Making Every Step Explainable
The trustworthiness of an intelligent coding system is built on explainability. It is recommended to continuously produce a structured event stream during task execution, including: plan generation events, step start/end events, tool invocation details, acceptance decision results, and plan revision records. These events can be used both for debugging and to show users “what the system is doing and why.” When a task fails, the event stream can quickly pinpoint whether it’s a planning deviation or an execution error, significantly reducing troubleshooting costs.
4. Typical Workflow Example
Using a “fix a failing test” task as an example, here is how the two layers collaborate:
- Planning Layer: Reads the failing test report, locates the relevant module, and formulates a plan—reproduce the failure, locate the root cause, modify the code, and run regression verification.
- Execution Layer: Runs the specified test command to reproduce the failure, returning the failing test case and assertion differences.
- Planning Layer: Infers potential defect locations based on the differences, issuing a step to “read the relevant source files and recent change logs.”
- Execution Layer: Returns file snippets and change summaries.
- Planning Layer: Formulates a modification plan, issuing precise editing steps and acceptance criteria (target test passes and no new failures in the full test suite).
- Execution Layer: Applies the modifications, runs the tests, and returns the results.
- Planning Layer: If acceptance passes, generates a change summary; if not, revises the plan based on new observations.
Throughout the process, every step has clear inputs, outputs, and acceptance criteria. Failures can be located, changes can be rolled back, and decisions can be traced.
5. Practical Recommendations and Conclusion
When implementing a layered collaborative architecture, it is recommended to follow these principles: start narrow, then expand, beginning with subtask types that have clear boundaries and explicit acceptance criteria, and gradually expanding task coverage; prioritize stability over speed, ensuring rollback and audit capabilities first before optimizing execution efficiency; maintain clear human-machine boundaries, preserving human confirmation for high-risk operations and positioning the system as a “controllable accelerator” rather than a “black-box agent.”
The layered collaboration of planning reasoning and execution operations essentially introduces proven software engineering principles into intelligent coding systems, such as “separation of design and implementation,” “traceable changes,” and “rollbackable failures.” It does not pursue the extreme capability of a single model call; instead, it trades architectural-level responsibility division and protocol constraints for improved overall task completion rates and controllable risks. For teams looking to introduce intelligent coding capabilities into real R&D processes, this layered approach offers greater long-term value than chasing the “most powerful combination” of a single tool.
