The Three-Layer Approach to Designing AI Coding Agents: Prompt, Context, and Control Engineering

    The performance of AI coding agents in long-running tasks relies heavily on engineering design outside the base model itself. This article explores a three-layer methodology—prompt engineering, context engineering, and control engineering—to systematically address how instructions are assembled, what the model is allowed to see, and how the system manages tool execution and error recovery.

    The performance of coding agents in long-running tasks largely depends on engineering design outside the model itself. The same base model, when accessed directly via API, often performs less stably than when integrated into a mature command-line tool. The gap typically stems from how instructions are assembled, what the model is allowed to see, and how the system handles tool errors.

    A common industry approach categorizes these efforts into three layers: prompt engineering, context engineering, and control engineering. They answer three questions respectively: what to say, what to let the model see, and in what environment to run. This division is not standardized, and different teams draw boundaries differently, but it helps developers troubleshoot issues layer by layer.

    I. Prompt Engineering: Dynamically Assembling Instructions by Task

    Early practices involved writing a fixed system prompt to cover all scenarios. However, the variety of coding tasks is too broad, and fixed prompts quickly become bloated, causing key constraints to be easily buried. The dynamic assembly approach suggests first identifying the current task, then loading only the relevant instructions, and supplementing with runtime environment information.

    1. Intent Recognition and Routing

    The system first classifies user input by intent. Common categories include bug fixing, code refactoring, writing new features, and answering questions. Each category corresponds to a template. For bug fixing, the template requires the model to read relevant test cases and error logs first, locate the call chain, and finally modify the code.

    Input/Output Example:

    • Input: “The login API occasionally returns a 500 error, can you take a look?”
    • Output: intent = bug_fix, confidence 0.86, load bug_fix template.

    If the confidence is below a threshold, such as 0.6, the system should not guess. It should confirm with the user: “Are you trying to fix an error or add a new feature?” This step costs very little but prevents the model from making extensive code modifications in the wrong direction.

    2. Environment Information Injection

    The prompt should also carry runtime environment information: operating system, language version, package manager and its version, and key dependencies in the lock file. Knowing the specific versions of project dependencies makes the model less likely to call non-existent APIs. This mitigates the “hallucination” problem but does not eliminate it entirely; subsequent checks are still required.

    Below is a runnable assembly function example showing how intent and environment are merged into the final system prompt:

    1. /**
    2. * @param {string} userIntent Intent category: 'bug_fix' | 'refactor' | 'feature' | 'question'
    3. * @param {{language: string, packageManager: string, os: string}} projectContext
    4. * @returns {string} The assembled system prompt
    5. */
    6. function buildSystemPrompt(userIntent, projectContext) {
    7. const parts = ["You are a senior developer, strictly following the project's existing code conventions."];
    8. const intentRules = {
    9. bug_fix: "Before modifying code, read relevant test cases and error logs, and explain the root cause.",
    10. refactor: "Maintain external behavior during refactoring, and run existing tests after each modification.",
    11. feature: "Before adding a new feature, confirm the interface conventions of existing modules.",
    12. question: "Only answer the question, do not modify any files.",
    13. };
    14. if (intentRules[userIntent]) {
    15. parts.push(intentRules[userIntent]);
    16. } else {
    17. parts.push("Intent is unclear, please confirm the task type with the user first.");
    18. }
    19. const languageRules = {
    20. python: "Follow PEP 8 code style and use a virtual environment to isolate dependencies.",
    21. javascript: "Follow the project's ESLint configuration, do not introduce dependencies not declared in the lock file.",
    22. };
    23. if (languageRules[projectContext.language]) {
    24. parts.push(languageRules[projectContext.language]);
    25. }
    26. parts.push(`The current operating system is ${projectContext.os}, and the package manager is ${projectContext.packageManager}.`);
    27. return parts.join("\n");
    28. }

    3. Common Errors and Checklist

    • Overly broad intent classification: A request includes both fixing a bug and adding a feature, causing conflicting templates. The solution is to split it into multiple sub-tasks and route them separately.
    • Outdated environment information: After the lock file is updated, the prompt still contains old versions. The solution is to re-read environment information at the start of each session.
    • Rule accumulation: Templates become too long, and the model starts ignoring some instructions. The solution is to periodically delete rules with no actual effect and verify changes using a fixed set of tasks.

    II. Context Engineering: Letting the Model See What It Needs to See

    Codebases usually far exceed the model’s effective context window. The problem context engineering solves is: within a limited token budget, let the model see as much relevant content as possible and less irrelevant content.

    1. Hybrid Retrieval

    Relying solely on vector retrieval easily leads to false recalls in code scenarios, as functions with similar semantics are not necessarily the correct call targets. A more robust approach is to combine multiple retrieval methods:

    • Parse function definitions, classes, and import relationships based on AST (Abstract Syntax Tree).
    • Traverse the function call graph to find upstream callers and downstream dependencies of the modified function.
    • Perform full-text search on keywords to cover error messages, configuration item names, and file paths.

    When the model needs to understand the usage of a function, the system should return both the definition and real call examples from the project. Call examples reflect actual conventions better than function documentation.

    2. Conversation History Compression

    In long tasks, conversation records and the agent’s intermediate reasoning expand rapidly. A common practice is a sliding window plus summarization: retain the full content of the most recent turns and compress earlier content into a summary. The summary should retain three types of information: key decisions, ruled-out incorrect directions, and explicit constraints from the user. Tentative intermediate outputs can be discarded.

    The most common issue with compression is losing constraints. For example, if a user says “do not change the public interface” and the summary omits this, subsequent modifications might break the interface. The verification method is to list all hard constraints separately and check whether each one still appears in the summary after every compression.

    3. Common Errors and Checklist

    • False recall: Irrelevant functions with the same name appear in the retrieval results. Check by sampling the top five recall results to confirm they have a dependency relationship with the current module.
    • Lost constraints in summary: Hard constraints disappear after compression. Check by maintaining a constraint list and verifying each item.
    • Context overload: Too many files are injected at once, making the model’s response generic. Check by limiting the number of files injected per turn and comparing modification quality across different limits.

    III. Control Engineering: Setting Constraints and Recovery Mechanisms Outside the Model

    Prompts and context primarily affect the model’s input. Control engineering affects the model’s actions: it determines how tools are executed, how errors are recovered, and which operations need to be intercepted.

    1. Error Classification and Recovery

    When executing terminal commands, …