Rules-Driven Development for AI Coding: A Practical Guide to Persistent Context
This article explains why AI coding assistants often underperform in real engineering environments and how Rules-driven Development solves the problem by turning implicit project knowledge into persistent, structured context. It covers the four layers of rule design (project, module, team, and personal), three trigger strategies (Always, Agent Requested, and Manual), how to write verifiable rules, how to embed rules into the development workflow, common anti-patterns, and a four-week rollout roadmap with simple metrics to measure impact.
1. The Problem: Why an AI That Can Code Is Still Not Enough
Over the past two years, AI coding tools have rapidly expanded their capabilities: code completion, refactoring, unit test generation, code explanation, and cross-file edits are now standard features. Yet in real engineering environments, many teams run into an awkward gap: the demo looks impressive, but the results on real projects fall short. The problem is usually not the model itself, but the model’s lack of project context.
An enterprise-grade codebase carries a large amount of implicit knowledge: why a module uses a particular layering approach, why error codes must be wrapped consistently, why logs must never print sensitive fields, why certain APIs must be designed to be idempotent. This knowledge typically lives scattered across design documents, code review comments, and the memory of senior engineers. AI cannot acquire it automatically. As a result, developers have to repeatedly supply background in each conversation, every session starts from zero, and the productivity gains are eaten up by the cost of rebuilding context.
The core idea of Rules-driven Development is to make this implicit knowledge explicit and structured, turning it into stable context that AI can read in every session. This upgrades a “one-off prompt” into an “accumulating asset.”
2. What Rules Really Are: Persistent Injection of System-Level Context
A rule file is not just a pile of prompt templates. It is a system-level context mechanism that works in three ways:
- Persistence: Rules exist as files in the codebase or local configuration and do not disappear when a session ends.
- Automatic injection: When a new session starts, rule content is loaded as background constraints, with no need for manual restatement.
- Shareability: Project-level rules live in version control alongside the codebase, so every team member gets a consistent behavioral baseline as soon as they pull the code.
This distinction is key: a prompt is a request, while a rule is a contract. A prompt influences a single output; a rule shapes long-term behavior.
3. Layered Design: Project, Module, Team, and Personal
A mature rule system is usually organized into four layers, each addressing problems at a different level of granularity.
The first layer is project-level rules, covering technology stack choices, directory structure, dependency management strategy, naming conventions, and commit and branch standards. It answers the question: what does this project look like?
The second layer is module-level rules, which add domain logic and constraints for a specific functional area. For example, the transaction domain must guarantee idempotency, and the search domain must limit the amount of data scanned per request. It answers the question: what special requirements does this part of the business have?
The third layer is team-level rules, which capture collaboration processes and quality gates. Examples include: API changes must be reflected in contract documentation, new public methods must come with unit tests, and a checklist of what code review should focus on. It answers the question: how do we work together?
The fourth layer is personal-level rules, which hold individual preferences such as comment density, variable naming taste, and exception handling style. These take effect only locally and do not pollute the team baseline. The value of this layering is avoiding “global rule bloat.” Stuffing everything into a single file eventually leads to conflicting rules and leaves the AI unable to identify what matters.
4. Trigger Strategy: Always, Agent Requested, and Manual
As the number of rules grows, the real question shifts from “should I write it” to “when should it take effect.” A common industry practice is to tag each rule with an application type:
- Always: For security and compliance red lines, such as no hard-coded secrets, no user privacy in logs, and parameterized SQL only. These rules must be injected unconditionally.
- Agent Requested: For reference documents and long guides, loaded only after the AI judges whether they are relevant to the current task, so the context is not crowded out by unrelated content.
- Manual: For operational playbooks tied to specific scenarios, activated when the developer explicitly references the rule name in the conversation.
The essence of this mechanism is context budget management. The context window is a scarce resource. Keeping thirty rules resident at all times is like asking the model to make decisions in noise. A sensible mix is usually: keep Always rules under ten, and make sure each is a decidable hard constraint; load long specifications on demand; trigger scenario playbooks manually.
5. How to Write Rules: Decidability First
The most common reason rules fail is that they are written like slogans. Statements such as “code should be elegant” or “comments should be clear” cannot be verified or enforced. High-quality rules have three traits: decidable, executable, and bounded.
---description: Data access layer standardalwaysApply: true---## Data Access Constraints1. All database access must go through the unified data access layer. Directly assembling queries in the business layer is forbidden.2. Query conditions must be parameterized. Concatenating user input into strings is forbidden.3. A single query must not return more than 500 records. Pagination is required beyond that.4. Write operations must explicitly declare transaction boundaries. Cross-table writes must not rely on implicit commits.## Counter-examples- Using the session object directly in a Controller to assemble a query is forbidden.
As the comparison shows, only when a rule states “what must be done,” “what is forbidden,” “what the threshold is,” and “what a counter-example looks like” does the AI have a stable basis for judgment. Rule entries should also stay orthogonal, so that two rules never issue contradictory instructions.
6. Integrating Rules into the Development Workflow: Making Them Actually Enforced
Rules that only sit in files will quickly rot. An effective way to put them into practice is to embed them into existing workflow stages:
- Requirements stage: Have AI generate an implementation plan and impact analysis based on project-level and module-level rules, aligning on the design before writing code.
- Coding stage: Always rules guard the security baseline, while on-demand rules supply domain details.
- Verification stage: Require AI to add unit tests and boundary cases according to team-level rules, and to self-check against the rule checklist.
- Review stage: Use the rule files as the review baseline. Issues that keep recurring in review comments should flow back into new rule entries.
The last step is especially important because it closes the loop: every manual correction is a rule candidate. If a team sticks to the principle that “any problem that appears more than twice must be written into a rule,” the rule library will become the team’s most valuable knowledge asset within a few months.
7. Common Anti-Patterns and How to Avoid Them
- Rule overload: Files run to thousands of lines and the AI cannot identify what matters. Split them into multiple rule files by topic and adjust trigger types.
- Vague rules: Using adjectives that cannot be verified. Replace them with thresholds, checklists, and counter-examples.
- Rule conflicts: Different files give opposite requirements for the same issue. Designate a single authoritative source and have the others reference it.
- Write-only, no maintenance: Rules go stale after a tech stack upgrade and end up misleading generation. Set up a quarterly review, and tag each rule with an update time and an owner.
- Leakage risk: Writing internal architecture details into personal-level configuration and syncing them to an external repository. Strictly separate project-level and user-level storage locations.
8. Rollout Roadmap
A practical approach is to work in two-week iterations across four steps. In week one, identify high-frequency rework points and select no more than ten hard constraints as the first batch of Always rules. In week two, add module-level rules and try on-demand loading. In week three, wire rules into the verification and review stages and collect violation samples. In week four, review the results: delete ineffective rules, merge duplicates, and fill in missing ones.
Three simple metrics can measure the impact: the share of AI-generated first-pass code that developers have to modify, the number of reviews bounced back for standard violations, and the time it takes a new member to go from pulling the code to producing compliant code. If all three keep declining, the rule system is starting to compound.
9. Conclusion
The productivity ceiling of AI coding tools does not depend on how strong the model is, but on whether you can pass organizational knowledge to it efficiently. Rules-driven Development offers a pragmatic path: organize knowledge with a layered structure, manage context with trigger strategies, guarantee enforcement with decidable phrasing, and achieve continuous evolution through a workflow loop. When the rule library becomes a carrier of team consensus, AI truly shifts from a “smart external consultant” to a “collaborator that knows the project.”
