Engineering Practices: From Out-of-Control to Controllable AI Coding Agents

    AI coding agents often run out of control, not because the models are weak, but due to a lack of engineering constraints. This article explores how to tame intelligent programming agents using project rule files, structured work modes, extension mechanisms like hooks and sub-agents, and a closed-loop system of permissions, acceptance, and metrics.

    Engineering Practices: From Out-of-Control to Controllable AI Coding Agents

    1. The Problem is Not “Weak Models”, but “Insufficient Engineering Constraints”

    When developers first encounter AI coding agents, they often expect them to act like senior engineers: understanding the project, following conventions, controlling the scope of changes, and delivering testable, reviewable code based on a single requirement. Reality often proves otherwise: asking it to modify three files might result in a dozen files being refactored; asking for a new feature might lead to the “optimization” of the core abstraction layer; repeatedly emphasized coding conventions might drift after a dozen rounds of conversation; and explicitly asking not to touch the dependency list may still yield hundreds of lines of unrelated changes.

    On the surface, this looks like the model is disobedient. Fundamentally, however, it is determined by the operating mechanism of the AI coding agent. A typical coding agent is not an IDE plugin with long-term memory, but an executor looping continuously around “Reasoning—Action—Observation”: it calls the model to generate the next action, executes a tool to read or modify files, feeds the tool result back to the model, and continues to the next round. It has no built-in task queue, state graph, or preset pipeline. It does not automatically know team conventions, directory boundaries, testing requirements, or deployment constraints. In every new session, the context window might be clean. Without persistent rules and runtime armor, the agent can only make temporary decisions based on the code it currently reads.

    Therefore, a truly usable AI coding agent is not an omnipotent assistant that works perfectly out of the box, but a production tool that requires engineering constraints. The goal of constraints is not to limit capability, but to channel it into a controllable track: let the agent understand the project from the very first message, give boundaries to every tool call, and ensure every round of changes can be verified and audited.

    2. Root Cause: Stateless Loops and Thin Decisions, Thick Runtime

    To understand the out-of-control phenomena, we must first understand the execution loop. A typical AI coding agent runtime can be abstracted as follows:

    1. while task is not completed:
    2. 1. Read current context and rules
    3. 2. Model infers the next action
    4. 3. Call tools (read files, search, edit, execute commands, etc.)
    5. 4. Write tool results back to context
    6. 5. Decide whether to continue or end

    This loop has several key characteristics:

    1. Stateless by design. A new session does not automatically inherit the full context of the previous one. The agent’s understanding of the project comes from the files, rule files, and conversations read in the current round.
    2. Thin decision logic, thick runtime armor. What really determines “whether it can be changed, where to change, and how to verify” is often not the model itself, but access control, context compression, tool boundaries, security policies, and rule injection.
    3. The ReAct pattern amplifies local decisions. The agent determines its next step based on current observations in each round. Without a global plan, scope creep like “change wherever it reads” is prone to occur.
    4. Verbal instructions decay. Emphasized points in a conversation may be lost after context compression or in long conversations, whereas content written in rule files can be re-injected at the start of a session or after compression, forming persistent constraints.

    Therefore, the first principle of governing AI coding agents is: Move important rules from the chat box into the project, turn one-time reminders into executable constraints, and turn “please do not” into permissions and checks.

    3. The First Constraint: Project Rule Files, Making Agents Understand You from the First Message

    The project rule file is a configuration file that the AI coding agent reads at the beginning of each session. It enters the system prompt before the user’s first message, providing the agent with persistent knowledge about the project. More critically, after context compression, the rule file is usually re-read from disk and re-injected, whereas temporary requirements mentioned in the chat may be lost. This is why important conventions must be placed in rule files rather than repeatedly “nagged” in the chat.

    An effective rule file should not be a long project introduction, but an “executable contract”. It is recommended to include the following layers:

    1. # Project Rules
    2. ## 1. Project Overview
    3. - Tech stack: ...
    4. - Core modules: ...
    5. - Directories forbidden to change: ...
    6. ## 2. Directory Map
    7. - src/domain: Domain models, changes require caution
    8. - src/api: Interface layer, follow unified response structure
    9. - tests/: Test cases, new features must add tests
    10. ## 3. Common Commands
    11. - Install dependencies: ...
    12. - Unit tests: ...
    13. - Static checks: ...
    14. - Build: ...
    15. ## 4. Coding Conventions
    16. - Use existing project style, do not introduce new styles
    17. - New public methods must have comments
    18. - Error handling must use unified exception types
    19. - Direct SQL concatenation in the business layer is prohibited
    20. ## 5. Change Boundaries
    21. - By default, modify a maximum of 5 files per task; exceeding requires prior explanation
    22. - Do not modify dependency lists, build scripts, or deployment configurations unless explicitly required by the task
    23. - Do not delete existing tests, do not skip failing tests
    24. ## 6. Acceptance Criteria
    25. - Must run relevant tests after changes
    26. - Must output change summary, impact scope, and uncovered risks
    27. - If unable to verify, clearly state the reason; do not assume passage

    Rule files should be short, layered, and maintainable. It is recommended that the project lead maintain the main rules, and the team update them through code reviews. Rules should be specific enough to be actionable, for example, “Do not change the dependency list” is more effective than “Modify dependencies with caution”. Rule files should also be versioned and evolve with the code to avoid becoming outdated documentation.

    4. The Second Constraint: Controlling the Pace with Plan, Execute, and Review Modes

    The stage where AI coding agents most easily go wrong is not writing code, but “starting to write without thinking clearly”. In engineering practice, work can be divided into three modes, with clear exit conditions for each.

    1. Plan Mode: Read Before Write, Proposal Before Change

    In Plan Mode, the agent is only allowed to read, search, and analyze, without directly writing files. It should output: task understanding, involved files, change steps, risk points, and test plan. The value of Plan Mode lies in turning “implicit reasoning” into an “explicit proposal”, allowing developers to correct deviations at a low cost. The exit condition can be: the proposal is confirmed, or the change scope and acceptance criteria are clear.

    2. Execute Mode: Small-Step Commits, Change Budget

    Execute Mode allows editing and running commands but must be constrained by a change budget. For example, a maximum number of files can be modified per session, cross-layer refactoring is prohibited, and relevant checks must be run after completing a sub-task. Execute Mode requires the agent to follow the “Read-Modify-Verify” closed loop, rather than generating a large diff at once and waiting for humans to clean up.

    3. Review Mode: Independent Perspective, Checking Conventions and Risks

    Review Mode can be executed by the main agent switching roles or by a sub-agent. It does not continue to expand features, but checks: whether it is out of scope, whether rules are violated, whether tests are added, whether sensitive operations are introduced, and whether error handling is missing. Review Mode outputs a list of issues and fix suggestions, and if necessary, returns to Execute Mode for minor fixes.

    The core of these three modes is not the form, but the stage gates: no execution without a plan, no completion without verification, and no merge without review. For complex tasks, an Exploration Mode can also be added, solely for locating code and gathering evidence.

    5. The Third Constraint: Three Extension Mechanisms - Hooks, Skill Libraries, and Sub-agents

    Rule files alone are not enough. Rules solve “what to know”, while extension mechanisms solve “how to execute stably”.

    1. Hook Mechanism: Embedding Critical Checks into the Lifecycle

    Hooks are check logic triggered before and after tool calls, at the start of a session, or at the end of a task. They are suitable for deterministic constraints: preventing writes to sensitive directories, auto-formatting after edits, running tests before commits, recording audit logs, and detecting large-scale diffs. Hooks should not rely on the model’s self-awareness, but should be enforced by the runtime.

    1. # Pseudo configuration example, expressing general ideas only
    2. before_edit:
    3. deny_paths:
    4. - "config/prod/"
    5. - "deploy/"
    6. max_files_per_task: 5
    7. after_edit:
    8. run:
    9. - "format_check"
    10. - "unit_test_related"
    11. on_failure: "block_and_report"
    12. before_finish:
    13. require:
    14. - "change_summary"
    15. - "test_result"
    16. - "risk_note"

    The principle of hooks is: the closer to high-risk operations, the more proactive the checks should be; the more deterministic the rules, the less they should be left to natural language reminders.

    2. Skill Library: Precipitating Repetitive Tasks into Reusable Task Packages

    A skill library is not just a simple collection of prompts, but an encapsulation of “task template + operation steps + acceptance checklist”. For example, “adding a new API” can be solidified into: first read the API specification, then add the controller, service, test, and documentation, and finally run the specified checks. The skill library prevents the agent from reasoning from scratch every time and reduces the probability of convention drift.

    3. Sub-agents: Isolating Context, Collaborating by Division of Labor

    Complex tasks can be handled by different sub-agents taking on exploration, implementation, testing, and review roles. The value of sub-agents lies in context isolation and separation of duties: the exploration agent only locates issues, the implementation agent only makes small-scope modifications, and the review agent only finds errors. The main agent is responsible for summarizing and decision-making, preventing one context from bearing all responsibilities at once, which dilutes attention.

    The three mechanisms work together to form a pipeline: rule files provide persistent knowledge, hooks provide hard constraints, the skill library provides standard actions, and sub-agents provide role division. Together, they compress “free play” into “controlled execution”.

    6. Permissions, Acceptance, and Metrics: Forming a Closed Loop of Controllability

    Engineering constraints also require permission minimization and an acceptance closed loop. Sensitive files, production configurations, and deployment scripts should be read-only by default or require manual confirmation; command execution should distinguish between read-only commands and write operations; all tool calls should retain audit logs. For acceptance, each task should require a change summary, impact scope, test results, and uncovered risks. For metrics, you can track the unauthorized modification rate, rework rate, test pass rate, diff size per task, rule hit rate, and manual confirmation count. Metrics are not for evaluating the model, but for discovering rule gaps: if a certain type of violation occurs repeatedly, turn it into a hook; if a certain type of task requires repeated rework, precipitate it into a skill.

    In a cloud engineering system, these mechanisms can be combined with general capabilities: use container platforms to isolate execution environments, use logging services to record tool calls and audit information, use monitoring alerts to observe pipeline anomalies, and use object storage to archive rule versions and task artifacts. Cloud platforms like Baidu AI Cloud can provide foundational infrastructure for such engineering closed loops, but the core remains the combination of rules, permissions, acceptance, and metrics, rather than relying on a single-point tool.

    7. Implementation Checklist: Start Managing Your Agents Today

    1. Establish a project rule file, clearly stating the directory map, commands, conventions, restricted areas, and acceptance criteria.
    2. Default to planning before executing; complex tasks must output a change proposal.
    3. Set a per-session change budget; explain before continuing if exceeding the scope.
    4. Use hooks to enforce sensitive directory protection, format checks, relevant tests, and audit logs.
    5. Precipitate high-frequency tasks into a skill library to reduce free play.
    6. Use sub-agents to isolate exploration, implementation, and review duties to reduce context pollution.
    7. Every task must output a change summary, test results, and risk explanation.
    8. Regularly review violations and rework, and convert problems into rules or hooks.

    The ceiling of AI coding agents is high, but its default state is not “understanding you”. What truly makes it take off is not longer prompts, but engineering constraints: persistent rules, stage gates, hard checks, role division, and acceptance closed loops. By doing these well, the agent will transform from an uncontrollable code generator into a research and development partner that understands the project, follows conventions, and is auditable.