Four System-Level Rules for Constraining AI Coding Agents

    This article explains why AI coding agents tend to drift—adding unrequested code, making silent assumptions, and refactoring beyond scope—and presents four system-level rules to address it: think before coding, prioritize simplicity, make surgical changes, and drive execution by verifiable goals. It covers how to write these rules into a versioned project rule file, how to roll them out in stages, which metrics to track, and common pitfalls to avoid. Readers will learn a low-cost, repeatable engineering convention for improving the quality of AI-generated code.

    1. Background: Why AI Coding Assistants Drift

    After introducing large language models into daily development workflows, many teams run into the same pattern: a requirement is only two or three sentences long, yet the model delivers hundreds of lines of code; a request to fix a single boundary condition ends with the directory structure refactored; worse still, the model quietly makes a decision based on an unstated assumption and keeps building on it, so by the time the result is wrong, the error has already spread across multiple files.

    These behaviors are not random signs of a “less capable model.” They are systematic side effects of how generative models work, and can be understood on three levels:

    1. Probabilistic completion bias. The model’s objective is to produce the most likely continuation, and “most likely” often means “most complete, most like mature engineering.” As a result, it proactively fills in features it assumes you “should need.”
    2. Incomplete context. Natural-language requirements inherently contain information gaps. A human colleague would ask first; a model tends to fill those gaps with default values without explicitly stating what it filled in.
    3. No self-verification loop. Without an executable success criterion before delivery, the model cannot tell whether it actually completed the task, and can only wrap up based on “looks done.”

    The right governance approach, therefore, is not to “switch to a stronger model,” but to add checkpoints in the workflow that force uncertainty to become explicit. The industry has distilled this kind of constraint into rule files placed in the project root (commonly versioned along with the codebase and automatically loaded by AI coding tools at the start of a session), making the rules system-level constraints rather than ad hoc reminders. The four rules below are the most broadly applicable part of this practice.

    2. Rule 1: Think Before Coding

    Core requirement: No silent assumptions. Any uncertainty that affects the implementation path must be surfaced before any code is written.

    In practice, uncertainties can be grouped into three categories, each handled differently:

    • Requirement ambiguity: One description has two or more reasonable interpretations. List the candidate interpretations and their impact, and let the user choose.
    • Environment unknowns: Dependency versions, runtime frameworks, or existing conventions are unclear. Read the project’s configuration files and existing code style first, then state the assumptions you are relying on.
    • Trade-off conflicts: Performance versus readability, compatibility versus simplicity. Present the options and their costs instead of deciding unilaterally.

    An example snippet to put in a rule file:

    1. Before providing any code, first output:
    2. 1) My understanding of the requirement (no more than 5 lines)
    3. 2) Ambiguous points and candidate interpretations (if none, explicitly write "no ambiguity")
    4. 3) The files I will read and the existing conventions I will rely on
    5. If any ambiguity exists in 2), ask first; do not generate implementation code.

    The value of this rule is that it moves the cost of errors earlier. Correcting an assumption takes a few seconds; correcting an implementation built on a wrong assumption usually costs an entire round of rework.

    3. Rule 2: Simplicity First

    Core requirement: Target the minimum viable implementation. Reject speculative design and abstractions with no payoff.

    The criteria can be made concrete, which helps both automated checks and human review:

    • If logic can be expressed clearly with a small amount of code, do not introduce extra configuration layers, factory functions, or inheritance hierarchies;
    • Do not implement switches, plugin mechanisms, or multi-strategy dispatch that “might be needed in the future”;
    • Do not add types, constants, or utility functions that are not referenced by the requirement;
    • Do not create an abstraction interface for a single call site; introduce abstraction only after a second real call site appears.

    It is worth stressing that simple does not mean crude. Necessary error handling, input validation, and logging must be kept, but “defensive code” must not expand into comprehensive protection against every possibility. A practical self-check question: if this newly added code were deleted, would the requirement still hold? If yes, it is most likely noise.

    4. Rule 3: Surgical Changes

    Core requirement: The scope of changes must strictly equal the scope of the task, leaving no trace outside the diff.

    This rule targets the most easily overlooked form of “code pollution”: naming styles being unified, formatting tools being reconfigured, unrelated files being reordered, comments being rewritten. Each of these looks like an “improvement” on its own, but mixed into a functional change they make review ineffective and problem localization harder.

    Suggested constraint wording:

    1. - Only modify the files and lines necessary to complete the task;
    2. - Do not refactor along the way, and do not unify existing naming or formatting styles;
    3. - Do not upgrade or add dependencies unless the task explicitly requires it;
    4. - If you judge that a change is necessary somewhere, explain why and get confirmation first.

    Paired with good engineering habits, the effect is more pronounced: keep each change single-purpose so it is easy to roll back; split formatting and refactoring into separate commits; require the model in the rule file to output a change list mapped item by item to requirement entries. Reviewers can then quickly verify changes with a one-to-one “requirement-to-change” mapping.

    5. Rule 4: Goal-Driven Execution

    Core requirement: Translate vague instructions into verifiable success criteria. Define how to verify before writing the implementation.

    Verifiable criteria usually come from three sources: executable automated tests, observable runtime results, and measurable metrics. The recommended sequence is:

    1. Rewrite the requirement into several acceptance conditions that can be judged true or false;
    2. Add a minimal verification method for each condition (a test case, a script, or manual check steps);
    3. Put the verification methods in place first, then write the implementation;
    4. Run the verification yourself, deliver only after everything passes, and attach the execution results.

    An example of how to express acceptance conditions:

    1. Acceptance conditions:
    2. - When the input is empty, return an explicit error code and do not throw an uncaught exception
    3. - When the input contains 10,000 records, processing time does not exceed the agreed threshold
    4. - All existing test cases remain passing (no regressions)

    When a verification method cannot be automated, explicitly state “this item requires manual verification” rather than skipping it by default. This step is key to whether the whole rule set closes the loop: without executable criteria, the first three rules degrade into verbal agreements.

    6. How the Four Rules Work Together and How to Adopt Them

    The four rules are not a parallel checklist but a chain: the thinking phase eliminates assumption divergence, the simplicity principle controls implementation size, the surgical-change principle constrains the scope of impact, and goal-driven execution closes the loop with verification. Missing any link weakens the effect of the other three.

    Adoption can proceed in three steps:

    • Step 1: Team alignment. Write the four rules into a rule file in the project root and put it under version control, so the rules evolve along with code review instead of staying as individual habits.
    • Step 2: Tiered rollout. Enforce them on core modules and shared libraries; relax them appropriately for exploratory scripts and temporary verification code, so the cost of the rules does not exceed the benefit.
    • Step 3: Measure and improve. Track three signals: rework rounds, proportion of unrelated changes, and defect escape rate. If rework rounds drop but unrelated changes do not decrease, the surgical-change constraint is not being truly enforced, and change-list verification needs to be strengthened.

    For teams with a unified development process and cloud-based development environments, the rule file can be distributed as part of an engineering template, and combined with common cloud capabilities such as container platforms, logging services, and monitoring and alerting, “whether verification passed” can be turned from manual confirmation into a continuously observable pipeline signal. In this kind of development-process standardization and observability work, Baidu AI Cloud typically provides support through combinations of general-purpose capabilities.

    7. Common Pitfalls

    • Treating rules as prompts. Rules are binding only when they are automatically loaded and contain decidable clauses.
    • Too many rules. Once the number of clauses exceeds a certain point, model compliance drops; keep the minimum necessary set.
    • Constraining without verifying. Rules without execution criteria cannot prove they are effective or be improved continuously.
    • Enabling everything at once. Forcing all rules onto rapid prototyping slows down exploration.

    Overall, improving the quality of AI coding output depends not on pursuing stronger generation capability, but on making uncertainty management, change-scope control, and result verification defaults in the workflow. These four rules are extremely low-cost and highly reproducible, making them a suitable first engineering convention when a team introduces AI coding tools.