Building an AI Coding Agent for Real Development Workflows from Scratch

    This article explains why a practical AI coding agent requires more than a model API and outlines the engineering design needed to make one controllable and extensible. It covers model adapters, context construction, tool abstraction, task state machines, code modification strategies, verification loops, security and auditability, engine replaceability, and a phased implementation roadmap.

    In recent years, AI coding tools have gradually evolved from code completion into AI coding agents that can understand projects, modify files, execute commands, and complete multi-step tasks. They are no longer just question-and-answer windows inside an editor. They are beginning to participate in the full software engineering workflow: requirements analysis, code search, solution design, implementation, testing, and repair.

    However, after actually trying to build such systems, it becomes clear that the hard part is not merely integrating a large model API. The model itself is only the reasoning core. Whether it can form reliable development capabilities depends on a series of engineering designs: context organization, tool abstraction, task state management, error recovery, security controls, and result verification.

    This article does not discuss a specific product. Instead, it explains from a general technical perspective why an AI coding agent needs to be redesigned and how to turn it into an engineering system that is controllable, extensible, and suitable for real projects.

    1. The Real Reasons to Rebuild

    When many people first encounter AI coding tools, the experience can be impressive. A user enters a natural-language instruction, and the system can generate code, modify files, or even attempt to run tests.

    But when the task changes from “write a function” to “modify a real project,” problems quickly emerge.

    1.1 Context Is Not the Same as File Contents

    The effective context of a project usually includes:

    • directory structure;
    • build configuration;
    • dependency relationships;
    • type definitions;
    • database models;
    • test cases;
    • historical changes;
    • current workspace state;
    • error logs and runtime environment.

    If the system simply concatenates the full text of several files and sends them to the model, three problems usually appear.

    First, input length grows rapidly, increasing cost and latency. Second, a large amount of content unrelated to the current task dilutes the focus. Third, the model may not be able to accurately determine which files are sources of facts and which are only background information.

    Therefore, one of the core capabilities of an AI coding agent is not “loading more text” but “selecting more suitable context for the current task.”

    1.2 A Single Generation Cannot Cover the Full Engineering Workflow

    Real development tasks often have clear stages:

    1. Understand the requirement;
    2. Locate relevant files;
    3. Analyze the existing implementation;
    4. Create a modification plan;
    5. Edit code;
    6. Run checks;
    7. Read errors;
    8. Fix problems;
    9. Verify again;
    10. Summarize changes.

    If the system makes only one model call, it is difficult to complete this loop. A more reliable approach is to let the model act step by step in a constrained environment and continuously update its judgment based on tool results.

    This means the system must support iterative execution, not a simple “input question—output answer” interaction.

    1.3 Model Capabilities Need Engineering Constraints to Be Stable

    A model may exhibit the following behaviors:

    • modifying unrelated files;
    • repeatedly executing the same command;
    • ignoring test failures;
    • misinterpreting command output;
    • generating paths that do not exist;
    • guessing project structure without sufficient evidence;
    • performing high-risk operations in order to complete a task.

    These problems cannot be solved entirely through prompts. They must be constrained through mechanisms such as tool allowlists, parameter validation, operation confirmation, execution timeouts, change auditing, and state machines.

    Therefore, the goal of rebuilding an agent is not to give the model unlimited permissions, but to let the model complete work as complex as possible within clear boundaries.

    2. Overall Architecture Design

    A practical AI coding agent can usually be divided into the following modules:

    1. User request
    2. ↓
    3. Task parser
    4. ↓
    5. Context builder
    6. ↓
    7. Model adapter layer
    8. ↓
    9. Task planning and tool-call loop
    10. ↓
    11. File operations / search / command execution / test verification
    12. ↓
    13. Result aggregation and change audit

    The model adapter layer communicates with different inference engines. The context builder organizes project materials. The tool layer provides real operational capabilities. The execution loop controls task progress. The audit module records every change and command.

    This layered design has two important benefits.

    First, it reduces coupling. When changing models, there is no need to modify file operations and task management logic. Second, it makes testing easier. Context construction, tool parameter validation, and state transitions can be verified separately without calling a real model every time.

    3. Model Adapter Layer: Do Not Bind Business Logic to a Single Engine

    Different model engines may differ in request formats, streaming output, tool-call representation, and error handling. If business code depends directly on one request structure, later expansion becomes very difficult.

    A more reasonable approach is to define an internal unified protocol, for example:

    1. type ChatMessage = {
    2. role: "system" | "user" | "assistant" | "tool";
    3. content: string;
    4. };
    5. type ToolCall = {
    6. name: string;
    7. arguments: Record<string, unknown>;
    8. };
    9. interface ModelAdapter {
    10. generate(input: {
    11. messages: ChatMessage[];
    12. tools?: ToolDefinition[];
    13. }): Promise<{
    14. text?: string;
    15. toolCalls?: ToolCall[];
    16. finishReason?: string;
    17. }>;
    18. }

    Upper layers only care about “sending messages and receiving text or tool calls”; they do not care about the underlying protocol.

    The adapter layer should also handle the following concerns uniformly:

    • network timeouts;
    • retry strategies;
    • streaming output;
    • authentication failures;
    • empty responses;
    • malformed tool parameters;
    • server-side rate limiting;
    • interrupting and cancelling tasks.

    Retries must not be unconditional. For read-only requests, a limited number of retries is usually safe. For operations that may have side effects, repeated execution caused by network anomalies must be avoided.

    4. Context Engineering: Show the Model What Actually Matters

    Context construction can be divided into four layers.

    4.1 Project-Level Context

    Project-level information includes language type, build method, test commands, directory conventions, and major modules. This information can be collected at the start of a session and stored as a summary.

    For example:

    1. Project type: server-side application
    2. Main language: type-safe scripting language
    3. Entry directory: src
    4. Test directory: tests
    5. Build method: configuration-file driven
    6. Current branch has uncommitted changes: yes

    Project-level context should not contain large amounts of source code. It should provide navigation information.

    4.2 File-Level Context

    When the model needs to modify a module, it should first receive:

    • file path;
    • file purpose;
    • relevant exports;
    • dependent files;
    • key types;
    • tests that may be affected.

    Compared with stuffing in the entire project, retrieving relevant files by task can significantly reduce noise.

    4.3 Operation-Level Context

    Every tool call should convert its result into structured information. For example, a search operation should return matching files and line numbers; file reading should clearly specify the path and range; test commands should distinguish standard output, error output, exit status, and runtime duration.

    Structured results are easier for the model to understand correctly than raw terminal text, and they are also easier to audit later.

    4.4 Historical Context

    Long tasks cannot retain all conversation indefinitely. The system can compress earlier processes into a summary and keep only:

    • completed items;
    • confirmed facts;
    • currently modified files;
    • unresolved problems;
    • the latest verification result;
    • next-step suggestions.

    This controls context size and reduces repeated review of irrelevant content by the model.

    5. Tool System: From “Callable” to “Controllable”

    Tools are the interface through which the agent connects to the real development environment. Common tools include:

    • file tree viewing;
    • file content reading;
    • keyword search;
    • structured code search;
    • file creation and modification;
    • patch application;
    • test execution;
    • static checks;
    • version diff viewing.

    Each tool should have clear input and output definitions. The model must not be allowed to concatenate arbitrary system calls directly.

    For example, a command execution tool should at least include:

    1. type CommandRequest = {
    2. command: string;
    3. cwd: string;
    4. timeoutMs: number;
    5. };

    Security checks are also required before execution:

    1. The working directory must be inside the project root;
    2. Access to sensitive system directories must be prohibited;
    3. Restrictions must be placed on operations such as deletion, overwriting, and network access;
    4. Processes must have timeouts;
    5. Output size must be limited;
    6. Full commands and exit statuses must be recorded;
    7. High-risk operations must require user confirmation.

    File modification should not default to overwriting the entire file. A safer approach is to generate a patch and, before applying it, check whether the target content still matches what the model read. This avoids incorrect overwrites caused by concurrent modifications or file changes.

    6. Task Loop and State Machine

    A simple but practical task loop can be abstracted as:

    1. Analyze request
    2. ↓
    3. Decide the next action
    4. ↓
    5. Call tools
    6. ↓
    7. Parse tool results
    8. ↓
    9. Check whether completion conditions are met
    10. ├─ No: continue acting
    11. └─ Yes: verify and output results

    To prevent the task from becoming uncontrolled, the loop needs explicit states:

    • planning: plan the task;
    • inspecting: read and search the project;
    • editing: generate or apply modifications;
    • testing: run verification;
    • repairing: fix based on errors;
    • completed: task completed;
    • failed: cannot continue;
    • cancelled: actively cancelled by the user.

    The value of the state machine is that the system no longer relies entirely on the model to “voluntarily follow the process.” For example, the system cannot enter the summary stage before code modifications are complete; test failures must record the reason; repeated operations in succession should trigger protection mechanisms.

    7. Code Modification Strategy

    Code modification is the step most likely to cause irreversible impact. The following process is recommended.

    Step 1: Read Before Writing

    The model must first read the target file and related dependencies. It cannot modify directly based only on the user’s description. For large files, it can read by range and use search results to locate key areas.

    Step 2: Plan Before Executing

    Complex tasks should first output a modification plan, including:

    • which files will be modified;
    • what change each file will contain;
    • whether new tests are needed;
    • which interfaces may be affected;
    • how to verify the result.

    The plan is not a formal document. It helps the model reduce omissions and gives the user an opportunity to correct direction before execution.

    Step 3: Use Minimal Patches

    Each modification should involve only the necessary lines where possible. Minimal patches are easier to review, roll back, and debug, and they reduce the risk of the model accidentally changing other logic.

    Step 4: Verify Immediately

    After completing a relatively independent modification, run format checks, type checks, or relevant tests as soon as possible. Do not wait until all files have been modified before verifying; otherwise, the error scope will become larger.

    8. The Verification Loop Is More Important Than Code Generation

    Whether an agent is practical depends not on how much code it generates the first time, but on whether it can find and fix its own errors.

    Verification can be divided into four layers:

    1. Syntax verification: ensure the code can be parsed;
    2. Type or static verification: find interface mismatches, undefined variables, and similar issues;
    3. Unit tests: verify local behavior;
    4. Integration verification: confirm that multiple modules work together correctly.

    After a test failure, the system should extract the most valuable information, such as failed test names, error locations, expected values, and actual values, instead of sending the entire log to the model indiscriminately again.

    At the same time, a repair limit should be set. If the same problem remains unresolved after multiple repair attempts, the loop should stop and explain the current state to the user. This prevents the system from continuously modifying code without clear progress.

    9. Security, Privacy, and Auditability

    An AI coding agent usually has permission to read source code and execute commands, so security capabilities must be treated as infrastructure rather than a later patch.

    First, apply the principle of least privilege by default. Allow access only to the current project directory, and expand the scope only when the user explicitly authorizes it.

    Second, identify and filter sensitive information to avoid sending keys, tokens, private configurations, and personal data directly to the model.

    Third, all changes should retain audit records, including:

    • who initiated the task;
    • what operations the model proposed;
    • what tools actually executed;
    • which files changed;
    • what the test results were;
    • whether human confirmation was obtained.

    Finally, the system should provide the ability to cancel a task at any time. Cancellation should not only stop the interface display; it should also terminate running subprocesses and ensure that the workspace state can be inspected by the user.

    10. Why the Engine Must Remain Replaceable

    An important consideration when rebuilding an agent is avoiding binding the system’s value to a single model engine.

    Different tasks have different requirements for models:

    • code completion values latency;
    • complex refactoring values reasoning capability;
    • daily search values cost;
    • test repair values long context and tool-call stability.

    If the system has a clear model adapter layer, it can select different engines based on task type and degrade gracefully when a service is unavailable.

    More importantly, models will continue to change, while tool orchestration, context management, security control, and auditing capabilities are often long-term assets. Only by accumulating these capabilities in the agent itself can business systems avoid frequent rewrites.

    If starting from scratch, it is advisable to implement the system in stages.

    In the first stage, support only project browsing, file reading, and search, with a focus on verifying whether context construction is accurate.

    In the second stage, add patch generation and human confirmation. Do not allow automatic execution of high-risk commands yet.

    In the third stage, add test execution and error feedback to form the most basic modification—verification loop.

    In the fourth stage, introduce the task state machine, historical summaries, concurrency control, and audit records.

    In the fifth stage, optimize prompts, tool granularity, model routing, and cost control based on real usage data.

    This progressive route is more reliable than attempting to achieve “fully automated programming” from the beginning. The core problems of an agent are often not a lack of features, but unclear boundaries, unrecoverable errors, and unverifiable results.

    Conclusion

    Rebuilding an AI coding agent is not simply connecting a model to a terminal or editor. It is essentially designing a new software engineering execution system: the model handles understanding and decision-making, tools handle actions, the state machine handles constraints, the verification mechanism handles confirmation, and the audit system handles tracking.

    A truly valuable system should have four characteristics:

    • it can understand a project, not just a single file;
    • it can execute multi-step tasks, not just generate a single answer;
    • it can verify and repair after failure, rather than continuing blindly;
    • it can control permissions and risk, rather than handing the entire environment to the model.

    Once these foundational capabilities are systematized, AI programming can gradually evolve from “occasionally impressive code generation” into dependable, maintainable, and auditable development infrastructure.