Engineering Guardrails for AI Coding Agents: From Chaotic to Controlled
AI coding agents often shine in demos but spiral out of control in real projects—expanding change scopes, touching forbidden files, and forgetting team conventions mid-session. This article argues the root cause is not model intelligence but missing engineering constraints, and presents a practical framework: persistent project-level configuration, three staged working modes (explore, plan, execute), three layers of guardrails (hooks, skills, role separation), feedback loops that make errors cheap and recoverable, and a phased rollout with measurable indicators. The goal is to turn probabilistic generation into engineering certainty.
Many teams go through the same disappointment when they first adopt an AI coding agent. In the demo, it reads the repository, fills in tests, and fixes bugs like a senior engineer on call. In a real project, the other side shows up quickly: you ask for three changes and it rewrites a dozen files; you explicitly forbid touching dependencies and build configuration, yet the commit is full of irrelevant diffs; it follows team conventions for the first few rounds, then reinvents its own style once the context grows long. The problem is not that “the model isn’t smart enough.” The problem is treating it as a plug-and-play black box without giving it the engineering constraints it needs to work reliably.
1. Understand Why Agents Go Off the Rails: Sessions Are Stateless, Verbal Rules Don’t Survive
A general-purpose coding agent typically runs a loop close to the ReAct paradigm: it observes the current context, reasons about the next action, calls tools for reading, writing, searching, terminal commands, or tests, then feeds the results back into context and repeats. It may look like it “plans,” but fundamentally it is conditional generation, turn by turn. The quality of each turn depends on whether the visible context is complete, whether permission boundaries are explicit, and whether feedback signals arrive in time.
Most of these systems are session-based. A new session does not naturally inherit memory from previous ones, and it does not automatically know which directories are generated artifacts, which modules are off-limits for refactoring, or which checks must run before a commit. If rules exist only in the chat, they are lost the moment context gets compressed, the window gets truncated, or a different person takes over. “Going out of control” is not an occasional mood swing; it is the inevitable result of missing persistent configuration, missing guardrails, and a missing verification loop.
So the first step is not better prompt wizardry. It is accepting one principle: important rules must live in machine-loadable engineering assets, not in reminders people repeat in conversation.
2. Carry “Long-Term Memory” in Project-Level Configuration
Create a project-level configuration file at the repository root. The name is up to you—AGENT.md, CONTRIBUTING-AI.md, or a team-wide assistant convention file. It should be explicitly referenced or automatically injected at the start of every task. Its content should not read like prose; it should be as short, deterministic, and executable as an interface contract. It should cover at least six categories:
- Project map: where the core entry points, domain modules, shared layers, generated directories, and third-party adapters live;
- Red-line list: lock files, migration scripts, key samples, infrastructure definitions, and compatibility-layer code that must not be modified;
- Coding conventions: naming, exception handling, log fields, test layering, commit message format;
- Verification commands: static checks, unit tests, integration tests, builds, and a minimal smoke path;
- Change policy: small commits, read before write, no scope expansion, record code smells without refactoring them on the spot;
- Escalation path: how to ask when requirements are unclear, and when to stop when risk exceeds a threshold.
The key insight is that configuration must be “reloaded,” not merely “mentioned once.” After context compression, verbal preferences vanish, but on-disk rules can be restored. For especially critical constraints, place them redundantly in the configuration file, templates, check scripts, and review checklists, so no single point of failure can erase them.
An example configuration might look like this:
# Repository Collaboration Rules- Goal: This repo is the order-domain service. Cross-domain changes to database schemas are forbidden.- Read-only zones: /infra, /migrations, /generated, dependency lock files.- Change zones: /src/order, /tests/order.- Required checks: lint, unit:test, api:contract:check.- Forbidden: large-scale renames without an Issue; public interface changes without updated contract tests.- Stop conditions: when new dependencies, cross-team interfaces, data backfills, or permission changes are needed, output the impact scope first and wait for confirmation.
3. Three Working Modes: Align First, Act Second, Verify Last
Splitting collaboration into modes dramatically reduces accidental damage. The first is explore mode: the agent reads but never writes, and outputs call chains, data flows, risk points, and candidate approaches—ideal for investigating unfamiliar modules. The second is plan mode: given a clear objective, the agent first proposes the minimal change set, affected files, a rollback plan, and a test strategy, and only proceeds after human approval. The third is execute mode: operations are strictly limited to the approved list; each completed slice triggers its corresponding verification, and any failure stops the work. There is no “while I’m at it” optimization to mask problems.
In practice, assign different permissions per mode. Explore mode disables write tools. Plan mode may generate patch drafts but must not write to disk. Execute mode opens restricted write access and limits terminal commands to a whitelist. Mode switches should be explicitly recorded—for example, as status transitions on a task card—so a vague “use your judgment” doesn’t blur exploration, refactoring, and shipping into one undifferentiated stream.
4. Three Layers of Guardrails: Hooks, Skills, and Role Separation
The first layer is hooks: automated checks triggered by events, rather than trusting the model to behave. Run formatting and secret scanning before saving; block oversized diffs, lock file changes, and public interface modifications without updated tests before committing; run contract tests and coverage thresholds before pushing. Terminal commands should be graded by semantics, with destructive, migration, and network-publish operations requiring a second confirmation. Hooks should return structured reasons—telling the agent which rule, which file, and how to fix it—instead of a bare failure.
The second layer is skills: encapsulate high-frequency tasks into reusable workflows, such as “add a new endpoint,” “backfill regression tests,” “trace production logs,” or “perform a security-driven dependency upgrade.” Each skill defines its inputs, steps, outputs, definition of done, and rollback actions, reducing improvisation. Skills should stay small; several small, deterministic skills beat one all-purpose mega-prompt.
The third layer is role separation: a planner handles decomposition and risk; an executor makes controlled changes; a reviewer focuses on boundaries, compatibility, and security; a tester only fills in failing paths. These roles can be a mix of humans and machines, or the same assistant under different role prompts in different contexts. The value is not ceremony but the separation of intent from power: whoever drafts the plan does not directly modify critical paths, and whoever changes code must pass independent review.
5. Build a Feedback Loop: Make Errors Cheap and Recovery Fast
The hallmark of a controlled system is not that it never errs, but that errors are caught early, contained narrowly, and easy to roll back. Treat every agent output as an ordinary change: small batches, traceable, reversible. Keep each commit to a single intent; have the agent list assumptions, uncovered cases, and next steps in its summary. When verification fails, preserve the scene and output a minimal reproduction instead of continuing to make sweeping edits. For recurring problems, go back and fix the configuration and hooks—don’t just repeat the reminder in chat.
You can also establish a rule-evolution mechanism: sample the agent’s commits weekly and track unauthorized modifications, useless refactors, test escapes, and style regressions. Convert high-frequency defects into new red lines or check items, and push constraints that have proven stable from prompts down into scripts and pipelines. In this way, team conventions gradually settle from individual experience into versioned assets.
6. Rollout Path and Success Metrics
You don’t need everything at once. In week one, do only three things: write the project configuration, lock down read-only zones, and wire up pre-commit checks. In week two, introduce the three modes and a change-approval checklist. In week three, codify two high-frequency skills and add contract or regression tests. At maturity, consider multi-role review, risk grading, and unified policy distribution across cloud development environments. Whether deployed locally or in a general-purpose development environment such as Baidu AI Cloud, the principles stay the same: least privilege, versioned rules, auditable execution.
Don’t measure success by how much text the agent generates in one shot. Track four indicators instead: whether the share of irrelevant diffs is falling, whether rework rounds are shrinking, whether pre-commit interception is moving earlier, and whether the first-pass review approval rate for agent output is rising. When these metrics improve, the agent is starting to respect project boundaries. When rules hold steady regardless of who is prompting, the team has truly folded probabilistic generation into engineering certainty.
One last thing to remember: an AI coding agent is not a wish-granting machine—it is a high-powered device that needs power, grounding, and a fuse. CLAUDE-style configuration solves “remembering,” modes solve “working in stages,” hooks solve “blocking in time,” skills solve “executing steadily,” and role separation solves “clear accountability.” Combine them, and chaos becomes control; the impressive demo becomes everyday productivity.
